考虑这个简单的例子:
class Foo
{
public int a;
public int b;
public int c;
public List<Foo> foos; // This complicates matters a bit
}
现在我想计算任何成员的总和/最小值/最大值/平均值等 - 包括 Foo
子级。我想为此创建一个通用函数,这样我就不必重复代码。
我想象这样的函数调用:
double sum = Calculate<double>(someFoo, sum => (f => f.a));
int count = Calculate<int>(someFoo, count => (f => 1 + foo.Length));
因此,对 Foo
的任意成员进行任意操作。这可以在 C# 4.0 中完成吗?例如。使用 Actions ?
最佳答案
编写一个辅助函数,为您提供所有 Foo
:
IEnumerable<Foo> SelfAndDescendants
{
get
{
yield return this;
foreach(var child in foos)
foreach(var descendant in SelfAndDescendants(child)
yield return descendant;
}
}
然后您可以简单地使用普通的 LINQ 进行聚合:root.SelfAndDescendents.Sum(f=>f.a)
如果您想进一步提高可重用性,您可以使用通用辅助函数:
public static IEnumerable<T> DepthFirstTopDownTraversal(T root, Func<T, IEnumerable<T>> children)
{
Stack<T> s=new Stack<T>();
s.Push(root);
while(s.Count>0)
{
T current = s.Pop();
yield return current;
foreach(var child in children(current))
s.Push(child);
}
}
然后将SelfAndDescendats
实现为return DepthFirstTopDownTraversal(this, f=>f.foos);
。
关于c# - 任意成员变量的任意计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086024/