【问题标题】:C#: Check whether an object is derived from class described by a Type objectC#:检查对象是否派生自 Type 对象描述的类
【发布时间】:2013-11-23 16:22:07
【问题描述】:

我有一个 Type T,我是通过 assembly.GetType("namespace.TypeName") 从程序集中加载的,还有一个未知类的 object o,从不同的地方收到。

我需要检查o是否派生自T

我试过了:

  • T.IsInstanceOfType(o),它不能按预期工作,正如 here 所解释的那样
  • o is T,产生编译器错误'T' is a 'field' but a 'type' was expected

感谢您的帮助。

【问题讨论】:

    标签: c# inheritance reflection types


    【解决方案1】:

    看看IsAssignableFrom Method

    Type t = ...
    Object o = ...
    
    bool isODerivedFromT = (o == null) || t.IsAssignableFrom(o.GetType());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 2012-09-06
      • 2018-09-10
      • 2020-09-01
      • 2010-11-15
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多