C# 如何使用反射在泛型类型中动态确定属性属于基类还是子类?
我有以下两个类(模型),一个是基类,另一个是子类:C# 如何使用反射在泛型类型中动态确定属性属于基类还是子类?,c#,.net,generics,inheritance,reflection,C#,.net,Generics,Inheritance,Reflection,我有以下两个类(模型),一个是基类,另一个是子类: public class BaseClass { public string BaseProperty{get;set;} } public class ChildClass: BaseClass { public string ChildProperty{get;set;} } 在应用程序中,我使用泛型动态调用ChildClass List<string> prope
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);
}
List propertyNames=new List();
foreach(typeof(T).GetProperties()中的PropertyInfo信息)
{
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))
…我只想要那些在子类中的属性。这可能吗
您需要使用重载,该重载接受一个参数并包含BindingFlags.DeclaredOnly
标志
PropertyInfo[] infos = typeof(ChildClass).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
DeclaredOnly:指定只应考虑在所提供类型的层次结构级别声明的成员。不考虑继承的成员
我需要从基类获取派生类名和属性,但基类没有任何内容 根据最上面的答案,我使用了以下内容。。。希望它能帮助别人
public abstract class StorageObject
{
protected readonly string TableName;
protected readonly string[] ColumnNames;
protected StorageObject()
{
TableName = GetType().Name;
ColumnNames = GetType().GetProperties().Where(x => x.DeclaringType == GetType())
.Select(x => x.Name)
.ToArray();
}
}
public class Symbol : StorageObject
{
public string Name { get; private set; }
public bool MarginEnabled { get; private set; }
public bool SpotEnabled { get; private set; }
public Symbol(ICommonSymbol symbol)
{
Name = symbol.CommonName;
if (symbol is BitfinexSymbolDetails bsd)
{
MarginEnabled = bsd.Margin;
}
if (symbol is BinanceSymbol bs)
{
SpotEnabled = bs.IsSpotTradingAllowed;
MarginEnabled = bs.IsMarginTradingAllowed;
}
}
}
很好。我想你的意思是使用反射,而不是泛型?谢谢,这很有效:)你节省了我很多时间。谢谢,但它不会返回任何属性。我错过了什么吗。您可以检查我使用您的代码所做的一切。@KaranDesai,您需要包括我上面显示的三个BindingFlag。调用
GetProperties
而不指定任何BindingFlags时,它使用BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance
。因此,您可能希望在列表中包括BindingFlags.Static
;这取决于您想要检索什么,也是我提供BindingFlags文档链接的原因。感谢您的澄清。只声明的描述把我弄糊涂了。当我添加所有三个标志时,这也起了作用+1谢谢,但我不想要基类属性名。我只需要子类属性名。而且,一切都是动态发生的,所以我可能不会硬编码并分配nameofBaseType
变量。