问题 如何使用反射确定属性是否在泛型类型中动态属于Base类或子类?


我有两个类(模型),一个是基类,另一个是子类:

public class BaseClass
{    
     public string BaseProperty{get;set;}    
}

public class ChildClass: BaseClass    
{    
     public string ChildProperty{get;set;}    
}

在申请我打电话 ChildClass 动态使用泛型

List<string> propertyNames=new List<string>();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
      propertyNames.Add(info.Name);
}

在这里,在 propertyNames 列表,我正在获得财产 BaseClass 同样。我只想要那些在子类中的属性。这可能吗?

我尝试了什么?

  1. 试图将其排除在此之外
  2. 尝试确定该类是否是所提到的子类或基类 这里 但这也无济于事。

6943
2017-09-13 10:57


起源

不错的q。我认为你的意思是使用Reflection而不是泛型? - StuartLC
stackoverflow.com/questions/12667219/... - Ric


答案:


你可以试试这个

foreach (PropertyInfo info in typeof(T).GetProperties()
        .Where(x=>x.DeclaringType == typeof(T))) // filtering by declaring type
{
    propertyNames.Add(info.Name);
}

10
2017-09-13 11:01



谢谢你的工作就像一个魅力:)你节省了我很多时间。 - Karan Desai


使用一个简单的循环来获取基类属性名称

var type = typeof(T);

var nameOfBaseType = "Object";

while (type.BaseType.Name != nameOfBaseType)
{
    type = type.BaseType;
}

propertyNames.AddRange(type.GetProperties().Select(x => x.Name))

1
2017-09-13 11:39



谢谢,但我不想要基类属性名称。我只想要子类属性名称。此外,一切都是动态发生的,所以我可能不会硬编码和分配 nameofBaseType 变量。 - Karan Desai


...我只想要那些属于子类的属性。这可能吗?

你需要使用 的GetProperties 超载需要一个 的BindingFlags 论证并包括 BindingFlags.DeclaredOnly 旗。

PropertyInfo[] infos = typeof(ChildClass).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

DeclaredOnly:指定仅考虑在提供的类型的层次结构级别声明的成员。不考虑继承的成员。


1
2017-09-13 14:20



谢谢,但它没有给我任何属性。我错过了什么。你检查一下 演示 我使用你的代码。 - Karan Desai
@KaranDesai,你需要包含我在上面展示的三个BindingFlags。你打电话时 GetProperties 没有指定任何BindingFlags,它使用 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance。所以你可能想要包括在内 BindingFlags.Static 到列表;它只取决于你想要检索的内容,这也是我提供BindingFlags文档链接的原因。 - TnTinMn
谢谢你的澄清。 DeclaredOnly的描述使我困惑。当我添加所有三个标志时,这也有效。 +1 - Karan Desai