C#中的接口转换 [英] Interface Casting in C#

查看:134
本文介绍了C#中的接口转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


interface ITest{}

class MyClass{}

class Main {
     public static void main(String[] args) 
     {
         MyClass obj = new MyClass();

         ITest iObj = (ITest)obj;  //compiles fine --Line 2
         
         SomeMethod(obj);          // compile time error --Line 3
     }

     public static void SomeMethod(ITest test) {}

}


在上面的代码片段中,尽管MyClass没有实现ITest接口,但第2行的编译没有任何错误.这是有道理的,因为在运行时obj可以引用从MyClass派生并实现ITest的某些类的引用.

但是第3行给出了编译时错误(无法从MyClass转换为ITest),上面的解释在这里也不成立吗?

谢谢!!
Rahul


In above code snippet, though MyClass does not implement ITest interface, Line 2 compiles without any error. This makes sense, since obj at runtime can have a reference of some class derived from MyClass and implementing ITest as well.

But Line 3 gives compile time error (cannot convert from MyClass to ITest), does not above explanation holds true here as well ?

Thanks!!
Rahul

推荐答案

铸造是一种危险的野兽:在这种情况下,您告诉编译器您了解的程度超过了他所知道的(或者至少您假设您知道得更多... ;-)).
因此,通过强制转换,您可以将类型检查推迟到运行时.
这就是为什么我考虑投射代码气味的原因.
干杯
Andi
Casting is a dangerous beast: you tell the compiler in this case that you know better than he knows (or at least you assume you know better...;-)).
So, with casting you defer the type check to run time.
That''s why I consider casting a code smell.

Cheers
Andi


尝试一下
interface ITest{}
 
class MyClass{}
 
class Main {
     public static void main(String[] args) 
     {
         MyClass obj = new MyClass();
 
         ITest iObj = (ITest)obj;  //compiles fine --Line 2
         
         SomeMethod(obj);          // compile time error --Line 3
                   //you have pass obj rather than Iobj
                        // try this SomeMethod(IObj);
     }
 
     public static void SomeMethod(ITest test) {}
 
}



[edit]添加了代码标签[/edit]



[edit] added code tags [/edit]


这篇关于C#中的接口转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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