2017-09-13 68 views
11

我有以下两类(型号),一个是基类,另一个是子类:如何确定属性是否属于基类或子类动态使用反射的泛型类型?

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. 尝试过不包括它作为在本question
  2. 试图确定该类是否是子类或基类如所提here但这并没有帮助提及。
+3

不错q。我认为你的意思是使用Reflection而不是泛型? – StuartLC

+1

https://stackoverflow.com/questions/12667219/reflection-exclude-all-attributes-from-base-class-and-specific-attribute-from-al – Ric

回答

9

你可以试试这个

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

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

1

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

var type = typeof(T); 

var nameOfBaseType = "Object"; 

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

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

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

1

...我只希望这是在子类中的那些属性。这可能吗?

您需要使用GetProperties重载需要一个BindingFlags参数,包括BindingFlags.DeclaredOnly标志。

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

DeclaredOnly指定只成员在声明所提供的类型的层次水平应予以考虑。不考虑继承的成员。

+0

谢谢,但它不返回任何属性。我错过了什么。你检查这个[demo](http://rextester.com/MNAHMY33063)我使用你的代码制作的。 –

+1

@KaranDesai,你需要包含我上面展示的三个BindingFlags。当你在不指定任何BindingFlags的情况下调用'GetProperties'时,它会使用'BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance'。所以你可能想要将'BindingFlags.Static'包含到列表中;它只是取决于你想要检索的内容,并且是我提供了BindingFlags文档链接的原因。 – TnTinMn

+0

谢谢澄清。 DeclaredOnly的描述让我困惑。当我添加所有三个标志时,这也起作用。 +1 –