![](/img/trans.png)
[英]Why can unrelated c# interface references be compared without compiler error?
[英]in c# why I can cast an interface to any type without a compiler error
考虑以下代码
IDisposable foo = <something>;
ArrayList bar = (ArrayList)foo;
即使ArrayList没有实现IDisposable,它也会在没有警告的情况下进行编译。
似乎可以将任何接口强制转换为未实现该接口的类。 由于两者的类型在编译时都是显而易见的,因此编译器为何不对此进行验证?
它不能验证它,因为它可能是有效的强制转换。
public class Foo : ArrayList, IDisposable
{
...
}
public class Bar : IDisposable
{
...
}
Random rand = new Random();
public IDisposable SomtimesGetArrayList()
{
if(rand.Next(0,4) == 0)
return new Bar();
return new Foo();
}
//Elsewhere
IDisposable foo = SomtimesGetArrayList();
ArrayList bar = (ArrayList)foo;
在对SomtimesGetArrayList
的4个调用中,有SomtimesGetArrayList
将返回可以成功转换的对象。 对于编译器来说,检查每个代码路径并确保每种可能产生对象的可能方式都必须进行强制转换,这是过多的处理工作。
但是,如果您有一个sealed
类,则编译器可以做出更多假设,并且不需要检查所有路径就知道强制转换将始终失败,因此以下代码将无法编译 。
using System;
public class Program
{
public static void Main()
{
IDisposable foo = new Foo();
Bar bar = (Bar)foo;
}
}
public class Foo : IDisposable
{
public void Dispose()
{
}
}
public sealed class Bar
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.