接口实例VS类的实例 [英] Interface instantiation vs class instantiation
问题描述
可能有人请helpme明白,如果下面的代码相同。如果不是出了什么阶级和interfance实例之间的区别。
Could someone please helpme to understand if the following codes are same. If not what's the difference between class and interfance instantiation.
IUnityContainer container = new UnityContainer()
UnityContainer container = new UnityContainer()
据我了解Inteface只有方法签名,如果接口已被执行3班。不太清楚其中3实例将由上述第一条语句创建。
As far as I understand Inteface has only method signature and if the interface has been implemented by 3 classes. Not too sure which of the 3 instance would be created by first statement above.
三江源。
推荐答案
接口不能被定义实例化。你总是实例化的具体类。
Interfaces can't be instantiated by definition. You always instantiate a concrete class.
所以的两个的语句您的实例实际类型为 UnityContainer
。
So in both statements your instance is actually of type UnityContainer
.
的区别是第一个声明,至于C#而言,你的容器
是一些农具 IUnityContainer
,这可能具有 UnityContainer
不同的API。
The difference is for the first statement, as far as C# is concerned, your container
is something that implements IUnityContainer
, which might have an API different from UnityContainer
.
考虑:
interface IAnimal
{
void die();
}
class Cat : IAnimal
{
void die() { ... }
void meow() { ... }
}
现在:
IAnimal anAnimal = new Cat();
Cat aCat= new Cat();
C#糊涂账 anAnimal.die()
的作品,因为死()
在 IAnimal
。但它不会让你做 anAnimal.meow()
,即使它是一个猫
,而 ACAT
可以调用这两种方法。
C# knows for sure anAnimal.die()
works, because die()
is defined in IAnimal
. But it won't let you do anAnimal.meow()
even though it's a Cat
, whereas aCat
can invoke both methods.
当您使用的接口为你的类型你是,在某种程度上,丢失信息。
When you use the interface as your type you are, in a way, losing information.
不过,如果你有其他类狗
也实现 IAnimal
,您 anAnimal
可以引用狗
实例为好。这是一个接口的供电;你可以给他们实现它的任何类。
However, if you had another class Dog
that also implements IAnimal
, your anAnimal
could reference a Dog
instance as well. That's the power of an interface; you can give them any class that implements it.
这篇关于接口实例VS类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!