我有这样一个类Foo:
class Foo
{
public int id{get;set;}
public IEnumerable<Foo> Childs;
//some other properties
}
Run Code Online (Sandbox Code Playgroud)
现在我想在Foo-Object上处理一些业务逻辑,所有这些都是这样的孩子:
public void DoSomeWorkWith(Foo x)
{
var firstItem = new {level = 0, item = x};
var s = new Stack<?>(?); //What type to use?
s.Push(firstItem);
while(s.Any())
{
var current = s.Pop();
DoSomeBusiness(current.item);
DoSomeMoreBusiness(current.item);
Log(current.level, current.item.id);
foreach(Foo child in current.item.Childs)
s.Push(new {level = current.level + 1, item = child});
}
}
Run Code Online (Sandbox Code Playgroud)
我需要跟踪孩子的(相对)水平/深度.如何Stack<T>为匿名类型创建?当然我可以创建一个简单的类而不是匿名类(或更复杂的递归函数),但是如何在没有附加类的情况下解决这个问题呢?
怎么样:
public static Stack<T> CreateEmptyStack<T>(T template) {
return new Stack<T>();
}
...
var stack = CreateEmptyStack(firstItem);
Run Code Online (Sandbox Code Playgroud)
这使用泛型类型推断来处理T.
您可以将其放入这样的方法中:
public Stack<T> CreateStackWithInitialItem<T>(T initialItem)
{
var s = new Stack<T>();
s.Push(initialItem);
return s;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
public void DoSomeWorkWith(Foo x)
{
var s = CreateStackWithInitialItem(new {level = 0, item = x});
while(s.Any())
{
...
}
}
Run Code Online (Sandbox Code Playgroud)