我正在尝试循环浏览班级中的字段,将某种类型的字段放入列表中,然后返回该列表。我知道我缺少一些关键组件,但我无法弄清楚我做错了什么。这是我到目前为止所拥有的:
...
我需要将实际字段的列表作为指针返回,而不是数据的副本。任何帮助使其工作的帮助将不胜感激。
我删除了上面的代码(你应该仍然可以在历史记录中看到它),因为它令人困惑。这是更新的代码(删除了一些额外的东西),这要归功于 Competitive_tech 的回答:
string prop1;
BaseClass prop2;
SubClass prop3;
SubClass prop4;
public List<BaseClass> GetData()
{
List<BaseClass> DataList = new List<BaseClass>();
foreach (System.Reflection.PropertyInfo thisInfo in this.GetType().GetProperties())
{
var tempPropery = thisInfo.GetValue(this, null);
if (tempPropery.GetType().IsSubclassOf(typeof(BaseClass)) || tempPropery.GetType().Equals(typeof(BaseClass)))
{
DataList.Add((BaseClass)tempPropery);
};
}
return DataList;
}
上面的代码将允许您从您的类中获取特定基类型的所有属性并将它们返回到一个列表中。所以上面的代码会返回 prop2 - prop4。