Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

c# - 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()

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.

Thankyou.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Interfaces can't be instantiated by definition. You always instantiate a concrete class.

So in both statements your instance is actually of type UnityContainer.

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.


Consider:

interface IAnimal 
{
    void die();
}

class Cat : IAnimal 
{
    void die() { ... }
    void meow() { ... }
}

Now :

IAnimal anAnimal = new Cat();
Cat aCat= new Cat();

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...