【发布时间】:2010-12-18 23:14:42
【问题描述】:
例如:
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
但我只需要父类的属性
ChildProperty1 ChildProperty2 ParentProperty1 ParentProperty2
是否有任何可能的方法可以指定可以使用多少层次的层次结构,以便返回的结果符合预期?提前致谢。
【问题讨论】:
-
不是开箱即用的。不过,您可以编写一些自定义的东西来做到这一点。
-
不要在循环中使用字符串连接。
-
@Dmitriy Matveev:这只是为了测试结果。 =)
-
现在,我遇到了另一个问题...如果我不进行字符串连接,那么我可能需要将项目添加到通用列表中...我稍后会尝试解决这个问题。
标签: c# inheritance reflection properties