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
500 views
in Technique[技术] by (71.8m points)

c# - Cast interface to its concrete implementation object or vice versa?

In C#, when I have an interface and several concrete implementations, can I cast the interface to a concrete type or is concrete type cast to interface?

What are the rules in this case?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Both directions are allowed in Java and C#. Downcasting needs an explicit cast and may throw an Exception if the object is not of the correct type. Upcasting, however, needs no explicit cast and is always safe to do.

That is, assuming you have public interface Animal and two implementations of this interface, Cat and Dog....

Animal meowAnimal = new Cat();  // No cast required
Animal barkAnimal = new Dog();  // No cast required

Cat myCat = (Cat) meowAnimal; // Explicit cast needed
Dog myDog = (Dog) barkAnimal; // Explicit cast needed

Dog myPet = (Dog) meowAnimal; // Will compile but throws an Exception

and you'll want a try / catch around the explicit casts. In C# you have the useful as keyword:

Dog myDog = barkAnimal as Dog;
Dog myPet = meowAnimal as Dog;

No exception will be thrown, and myDog will be nonNull and myPet will be null. Java does not have an equivalent keyword although you can always use if (meowAnimal instanceof Dog) tests to keep type safety. (I would guess that the "as" keyword generates bytecode that does the if, assigning null of the is fails. But perhaps .NET has a bytecode instruction that does the equivalent of "as".)


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

...