声明接口的对象而不是实现类[重复]
Posted
技术标签:
【中文标题】声明接口的对象而不是实现类[重复]【英文标题】:Declaring object of interface instead of implementation class [duplicate] 【发布时间】:2013-05-05 01:21:15 【问题描述】:我发现这段代码创建了一个实现类的对象并将其分配给接口类变量:
Myinterface obj=new MyImplementationClass();
我们为什么不直接使用
MyImplementationClass obj=new MyImplementationClass();
?
【问题讨论】:
你对接口了解多少?听起来你最好阅读他们的介绍。 @noobob 好吧,这 有点 是的 - 如果你添加一些 COM 属性(以声明默认的具体类型),编译器会允许你:p 我猜,它有助于多态性,我们可以保存不同子类的对象,并决定每个子类在运行时的行为。如果我错了,你可以纠正我 @MarcGravell 在我看到你的回复之前删除了我的评论,但我不知道。感谢您的信息......并尊重:) @MarcGravell 'var' 关键字在哪里适合所有这些? 【参考方案1】:实现MyInterface
的类可能不止一个。如果你使用:
MyInterface obj = new MyImplementationClass();
你也可以这样做:
MyInterface obj = new MyOtherImplementationClass();
但是如果你使用具体的实现名称,你就不能这样做(*):
// This wouldn't work:
MyImplementationClass obj = new MyOtherImplementationClass();
您将无法使用以下内容:
MyInterface obj = new MyInterface();
因为你不知道什么是疯狂的。应该是MyInterfaceImplementation
吗?应该是MyOtherInterfaceImplementation
?
但是有一种技术叫做依赖注入。这让你以某种方式绑定一个特定的实现到一个类型。有了它,您可以执行以下操作:
MyInterface obj = dependencyInjectionContainer.Resolve<MyInterface>();
看看What is dependency injection?。
(*) 除非MyOtherImplementationClass
继承自MyImplementationClass
。
【讨论】:
非常感谢您给出如此明确的答复。已接受并 +1。 没问题,尽情学习吧!【参考方案2】:首先你不能创建接口对象。使用接口的第二点可以帮助您以最小的更改迁移到新的类实现
在您的编码位置,您将针对 Interface 而不是类,因此如果明天您更改了 Concrete 类,您只需在一个地方修改它,所有代码都会切换到新类。
【讨论】:
以上是关于声明接口的对象而不是实现类[重复]的主要内容,如果未能解决你的问题,请参考以下文章
当类实现相同的接口时,Lambda表达式因LambdaConversionException而失败? [重复]