铸造界面到其具体的实施对象或反之亦然? [英] Cast interface to its concrete implementation object or vice versa?

查看:186
本文介绍了铸造界面到其具体的实施对象或反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#,当我有一个接口和一些具体的实现,可我投的接口一个具体类型或具体类型强制转换为界面?

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?

推荐答案

这两个方向都允许Java和C#。向下转换需要一个明确的转换,如果对象是类型不正确可能会抛出异常。上溯造型,然而,需求没有明确的演员和工作始终是安全的事情。

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



,你会希望有一个尝试 / 周围的显式转换。在C#中你有有用关键字:

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;

没有会抛出异常,并myDog将非空和myPet将为空。 Java没有等效的关键字,虽然你总是可以使用如果(meowAnimal的instanceof狗)测试,以保持类型安全。 (我猜了关键字生成字节码,做的如果,分配的失败空。但也许.NET有一个字节码指令,可以做的相当于。)

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".)

这篇关于铸造界面到其具体的实施对象或反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆