[英]C# - How to properly use an implementation of an interface
public interface IMyInterface
{
List<string> MyList(string s)
}
public class MyClass : IMyInterface
{
public List<string> MyList(string s)
}
有什么区别:
[Method]
MyClass inst = new MyClass();
...
要么:
[Method]
var inst = new MyClass() as IMyInterface;
...
要么:
[Method]
IMyInterface inst = new MyClass();
...
使用IMyInterface的实现的正确方法是什么?
第二个是可怕的。 它真的相当于
IMyInterface inst = new MyClass();
但它甚至没有检查MyClass
实现了接口。 这只是一种使用var
的方法,但在其他地方明确指定类型。 伊克。
一般来说,使用接口类型声明变量更清晰(如上所述,或者第三个选项),如果这是您所依赖的 - 它使用户清楚地知道您不需要该类声明的任何额外成员。 请参阅“对接口进行编程意味着什么?” 欲获得更多信息。
请注意,这与实现接口无关。 MyClass
是实现接口的类。 这与使用接口的实现有关。
MyClass inst = new MyClass();
它使用具体类型创建对象。 多态性是不可实现的。
var inst = new MyClass() as IMyInterface
编译器能够根据强制转换推断它的类型。 类型是IMyInterface ...
IMyInterface inst = new MyClass();
在我看来最好的。 通过使用MyInterface,您可以实现多态,在运行时更改inst指向的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.