【问题标题】:Checking to see if a generic class is inherited from an interface检查泛型类是否从接口继承
【发布时间】: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


    【解决方案1】:
    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 开头)

      【讨论】:

        猜你喜欢
        • 2019-06-25
        • 1970-01-01
        • 2014-03-05
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2020-03-02
        相关资源
        最近更新 更多