接口实例化 vs 类实例化 [英] Interface instantiation vs class instantiation
问题描述
有人可以帮助我了解以下代码是否相同.如果不是,类和接口实例化之间有什么区别.
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#而言,你的container
是实现了IUnityContainer
的东西,它可能有一个不同于的APIUnityContainer
.
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()
可以工作,因为 die()
是在 IAnimal
中定义的.但是它不会让你做 anAnimal.meow()
即使它是一个 Cat
,而 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.
然而,如果你有另一个类 Dog
也实现了 IAnimal
,你的 anAnimal
可以引用一个 Dog
实例也是如此.这就是接口的力量;你可以给他们任何实现它的类.
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屋!