2010-03-30 53 views
2

我有一个继承自接口的类。该接口定义了一个我想在调用代码中订阅的事件。我尝试了几件事,但它们都解决了错误(我知道它是真的)。我如何检查一个类是否实现了特定的接口。检查通用类是否从接口继承

这里是我试过(注意,有问题的对象是实现MyInterface的一个用户控件,存储在控制器的阵列,其中只有一些实现MyInterface - 不是null):

if (this.controls[index].GetType().IsSubclassOf(typeof(MyInterface))) 
    ((MyInterface)this.controls[index]).Event += this.Handler; 

if (this.controls[index].GetType().IsAssignableFrom(typeof(MyInterface))) 
    ((MyInterface)this.controls[index]).Event += this.Handler; 

if (this.controls[index].GetType() == typeof(MyInterface)) 
    ((MyInterface)this.controls[index]).Event += this.Handler; 

一切都无济于事。

回答

6
if (typeof(MyInterface).IsAssignableFrom(this.controls[index].GetType())) 
    ((MyInterface)this.controls[index]).Event += this.Handler; 

您只需将IsAssignableFrom倒置。


对于你的情况,但是,最好的方式做这个测试是对性能和清晰的改进如下:

if (this.controls[index] is MyInterface) 
2

我可能是密集的,但你不能只是做:

MyInterface foo = this.controls[index] as MyInterface; 
if (foo != null) { /* do stuff */ } 

(当然真正MyInterface应该有一个名称以I