![](/img/trans.png)
[英]How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)
[英]How to get the properties of a class using reflection (specifying how many levels of hierarchy) in C#.Net?
因此,例如:
class GrandParent {
public int GrandProperty1 { get; set; }
public int GrandProperty2 { get; set; }
}
class Parent : GrandParent {
public int ParentProperty1 { get; set; }
public int ParentProperty2 { get; set; }
protected int ParentPropertyProtected1 { get; set; }
}
class Child : Parent {
public int ChildProperty1 { get; set; }
public int ChildProperty2 { get; set; }
protected int ChildPropertyProtected1 { get; set; }
}
但是當我這樣做時:
public String GetProperties() {
String result = "";
Child child = new Child();
Type type = child.GetType();
PropertyInfo[] pi = type.GetProperties();
foreach (PropertyInfo prop in pi) {
result += prop.Name + "\n";
}
return result;
}
函數返回
ChildProperty1
ChildProperty2
ParentProperty1
ParentProperty2
GrandProperty1
GrandProperty2
但我只需要直到Parent類的屬性
ChildProperty1
ChildProperty2
ParentProperty1
ParentProperty2
是否有任何可能的方法可以指定可以使用多少個層次結構,以便返回的結果將是所希望的? 提前致謝。
沒有。
if (prop.DeclaringType == typeof(Child) ||
prop.DeclaringType == typeof(Child).BaseType)
在result += prop.Name + "\\n";
之前添加上面的行result += prop.Name + "\\n";
您可以將BindingFlags.DeclaredOnly
與Type.GetProperties
一起使用,以僅搜索在Type上聲明的屬性,並排除繼承的屬性。 然后,您可以編寫一個方法,該方法獲取類型的屬性並針對指定的遞歸深度遞歸獲取其父類型。
string GetProperties(Type type, int depth)
{
if (type != null && depth > 0)
{
string result = string.Empty;
PropertyInfo[] pi = type.GetProperties(BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in pi)
{
result += prop.Name + "\n";
}
result += GetProperties(type.BaseType, depth - 1) + "\n";
return result;
}
return null;
}
例:
Console.WriteLine(GetProperties(typeof(Child), 2));
輸出:
ChildProperty1 ChildProperty2 ParentProperty1 ParentProperty2
我還沒有測試過,但是下面的方法應該可以解決問題。
IEnumerable<PropertyInfo> GetProperties(Type t, int depth) { List<PropertyInfo> properties = new List<PropertyInfo>(); if (type != null) { while (depth-- > 0) { properties.AddRange(type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) ; type = type.BaseType; } } return properties; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.