【发布时间】:2013-02-25 08:36:59
【问题描述】:
我有几个 get 属性,我希望它们能够像函数数组一样循环。我希望能够做这样的事情
public int prop1 { get; }
public string prop2 { get; }
public int[] prop3 { get; }
public int prop4 { get; }
public string prop5 { get; }
public string prop6 { get; }
Func<var> myProperties = { prop1, prop2, prop3, prop4, prop5, prop6 };
ArrayList myList = new ArrayList();
foreach( var p in myProperties)
{
myList.Add(p);
}
这段代码很糟糕,但我认为它传达了我希望能够做什么的想法。有谁知道我怎么能做到这一点?
【问题讨论】:
-
documentation for
Func<TResult>向您展示了至少四种正确创建它们的方法。此外,考虑到代码中有多少损坏,您应该花更多时间阅读 C# 教程。 -
如果不使用反射,您将不得不创建一个数据结构(例如
List)来保存对每个属性的引用;然后遍历该数据结构。
标签: c# arrays properties getter