我正在尝试循环遍历字段,将某个类型的字段放入列表中,然后返回该列表。我知道我错过了一些关键组件,但我无法弄清楚我做错了什么。这是我到目前为止有:返回类中的所有字段
...
我需要返回的实际字段列表为指针,而不是数据的副本。任何帮助,让这个工作,将不胜感激。
我删除了上面的代码(你应该仍然可以在历史中看到它),因为它很混乱。这是更新的代码(除去一些额外的东西),从competent_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。
我会用一个'词典<字符串,PrimaryAbility>'代替。那么你可以通过这种方式得到'STR':'var str = AllAbilities [“STR”];'。需要反思往往表明你应该重构你的代码。 –
我正在寻找一种简单(但在开始时很复杂)的方式来返回所有能力(和其他类使用相同的结构),而不是每次添加新内容时都必须添加额外的代码行。 –