【问题标题】:Why is my C# IS statement not working?为什么我的 C# IS 语句不起作用?
【发布时间】:2013-09-30 02:05:47
【问题描述】:

我有以下代码,其中 T 是这样定义的泛型:

public abstract class RepositoryBase<T> where T : class, IDataModel

这段代码运行良好:

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType.FullName == typeof(T).FullName)  <--- Works just fine

vs 这段代码的结果为假

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType is T) <-- does not work

我在这里做错了什么?

【问题讨论】:

标签: c# reflection properties


【解决方案1】:

is 使用两个对象之间的类型比较。所以DeclaringType 是Type 类型,typeof(T) 是T 类型,它们不相等。

var aType = typeof(propertyInfo.DeclaringType);
var bType = typeof(T);
bool areEqual = aType is bType; // Always false, unless T is Type

【讨论】:

    【解决方案2】:

    你要找的是

    TypeIsAssignableFrom

    if (propertyInfo.DeclaringType.IsAssignableFrom(typeof(T)))
    

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多