【发布时间】:2023-03-22 04:03:01
【问题描述】:
我有一个从接口继承的类。该接口定义了一个我想在调用代码中订阅的事件。我尝试了几件事,但他们都认为是假的(我知道这是真的)。如何检查一个类是否实现了特定接口。
这是我尝试过的(注意,有问题的对象是一个实现 MyInterface 的用户控件,存储在一个控件数组中,其中只有一些实现了 MyInterface - 它不为空):
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;
一切都无济于事。
【问题讨论】:
标签: c# inheritance interface