在C#中使用接口 [英] Using of Interfaces in C#

查看:73
本文介绍了在C#中使用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我对界面有点混乱。我知道接口的定义。但我不清楚何时何地将使用。请任何机构都可以解释一下。



另外一个疑问是,我们是否应该使用接口而没有在类中实现某些方法?因为,该方法不需要所有类的某些类。那些情况我们能做什么?

解决方案

请看这些过去的讨论:

当我们使用抽象时和使用界面时......? [ ^ ],

抽象类和接口之间的区别,如果它们具有相同的no方法和var [ ^ ],

如何决定选择抽象类或接口 [ ^ ],

接口和多态性 [ ^ ]。



关于你的上一个问题,这不太正确。 使用界面的概念非常模糊。将接口类型用作类型时,不会实现任何方法。但是,当您完成实现某个接口的某些 struct class 的代码时,所有接口方法都是完全实现的,否则代码将无法编译。您还可以使用(并且应该使用)接口作为某个变量或成员的编译时类型。但是,在运行期间,实际的运行时类型将始终是一些 struct class 。实际上,在你进入接口之前,你应该很好地理解运行时和编译时类型,通过继承,虚方法和方法覆盖,这是OOP的核心。



如果该方法不需要所有类,则可能只是意味着您的代码设计很糟糕。也许您需要查看大量用于界面的用例来理解它。



-SA


接口定义是类(实现时)必须遵循的合同。

接口通常用于改变实现,即使类符合普通合同。

这可能有所帮助 - 何时使用接口 [ ^ ]



在任何接口中定义的任何方法都必须在派生类中有一个实现。



几个初学者链接应该可以进一步帮助你。

C#界面(初学者) [ ^ ]

抽象类与接口 [ ^ ]

Hi all,

I have a little bit confusion of interfaces. I know definition of the interfaces.But I am not clear about when and where to will be used. Please any body can explain it.

And another doubt is, shall we used interface without implemented some method in to the class?. Because, that method is not need to all that classes either some classes. What can we do that situations?

解决方案

Please see these past discussions:
When we use abstract and when we use interface...?[^],
Difference between abstract class and interface if they have same no of methods and var[^],
How to decide to choose Abstract class or an Interface[^],
Interfaces and Polymorphism[^].

As to your last question, it is not quite correct. The notion of "using interface" is quite ambiguous. When you use the interface type as a type, none of the method is ever implemented. But at the point you complete the code of some struct or class implementing some interface, all interface methods are implemented in full, otherwise the code will not compile. You can also use (and should use) the interface as a compile-time type for some variable or member. But, during run-time, the actual run-time type will always be some struct or class. Actually, before you get to interfaces, you should understand very well the run-time and compile-time types, through inheritance, virtual method and method override, a heart of OOP.

If "that method is not need to all that classes", it may simply mean that your code design is just bad. Perhaps you need to review a good number of use cases for interfaces to understand it.

—SA


An interface definition is a contract that classes (when implementing) must follow.
Interfaces are commonly used to vary the implementation even though classes adhere to the common contract.
This may help -When To Use Interfaces[^]

Any method defined in any interface must have an implementation in the derived class.

A couple of beginner links should further help you out.
Interfaces in C# (For Beginners)[^]
Abstract Class versus Interface[^]


这篇关于在C#中使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆