我有两个类(模型),一个是基类,另一个是子类:
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
同样。我只想要那些在子类中的属性。这可能吗?
我尝试了什么?
- 试图将其排除在此之外 题
- 尝试确定该类是否是所提到的子类或基类 这里 但这也无济于事。
你可以试试这个
foreach (PropertyInfo info in typeof(T).GetProperties()
.Where(x=>x.DeclaringType == typeof(T))) // filtering by declaring type
{
propertyNames.Add(info.Name);
}
使用一个简单的循环来获取基类属性名称
var type = typeof(T);
var nameOfBaseType = "Object";
while (type.BaseType.Name != nameOfBaseType)
{
type = type.BaseType;
}
propertyNames.AddRange(type.GetProperties().Select(x => x.Name))
...我只想要那些属于子类的属性。这可能吗?
你需要使用 的GetProperties 超载需要一个 的BindingFlags 论证并包括 BindingFlags.DeclaredOnly
旗。
PropertyInfo[] infos = typeof(ChildClass).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
DeclaredOnly:指定仅考虑在提供的类型的层次结构级别声明的成员。不考虑继承的成员。