【问题标题】:How do you use the IS operator with a Type on the left side?如何使用 IS 运算符和左侧的 Type?
【发布时间】:2010-11-08 11:17:24
【问题描述】:

我正在编写一个使用反射来列出类的静态属性的方法,但我只对特定类型的属性感兴趣(在我的情况下,属性必须是从 DataTable 派生的类型)。我想要的是类似于下面的 if() 语句(目前总是返回 true):

PropertyInfo[] properties = ( typeof(MyType) ).GetProperties( BindingFlags.Public
    | BindingFlags.Static );

foreach( PropertyInfo propertyInfo in properties ) {
    if( !( propertyInfo.PropertyType is DataTable ) )
        continue;

    //business code here
}

谢谢,我被难住了。

【问题讨论】:

    标签: c# reflection static properties types


    【解决方案1】:
    if (!(typeof(DataTable).IsAssignableFrom(propertyInfo.PropertyType)))
    

    这里的顺序可能看起来有点倒退,但对于 Type.IsAssignableFrom,您希望首先使用需要使用的类型,然后是您正在检查的类型。

    【讨论】:

      【解决方案2】:

      您需要使用Type.IsAssignableFrom 而不是“is”运算符。

      这将是:

      if( !( DataTable.IsAssignableFrom(propertyInfo.PropertyType) )
      

      如果 PropertyType 是 DataTable 或 DataTable 的子类,DataTable.IsAssignableFrom(propertyInfo.PropertyType) 将为真。

      【讨论】:

        【解决方案3】:
        if( !( propertyInfo.PropertyType.isSubClassOf( typeof(DataTable) ) )
         continue;
        

        我认为应该这样做。

        【讨论】:

        • 如果 PropertyType 是 DataTable,那将失败。
        • 我不知道,但有道理。
        猜你喜欢
        • 1970-01-01
        • 2015-11-24
        • 2016-06-08
        • 2016-03-13
        • 2015-06-12
        • 2017-07-16
        • 2016-06-23
        相关资源
        最近更新 更多