(标题是不是很好,我应该......随意更改,我希望我可以用一个例子更好地表达自己)Foreach循环
我有以下类:
abstract class AbstractObject<T>
{
List<T> Children { get; protected set; }
}
class A : AbstractObject<A>
{
//I have access to a List<A>
}
class B : AbstractObject<B>
{
//I have access to a List<B>
}
然后,在某些时候,我有以下方法:
private TreeNode PupulateRecursively<T>(AbstractObject<T> _us)
{
if (_us.Children == null || _us.Children.Count == 0)
{
return new TreeNode(string.Format("{0} - {1}", _us.FormattedID, _us.Name)) { Tag = _us };
}
else
{
Debug.Assert(_us.Children.Count > 0);
TreeNode node = new TreeNode(string.Format("{0} - {1}", _us.FormattedID, _us.Name)) { Tag = _us };
foreach (var child in _us.Children)
{
TreeNode n = PupulateRecursively(child);
node.Nodes.Add(n);
}
return node;
}
}
但我发现了一个:The type arguments for method PupulateRecursively<T> (AbstractRallyObject<T>) cannot be inferred from the usage. Try specifying the type arguments explicitly.
,因为child
这个foreach中的var是T类型的。
我该如何解决这个问题?这是一个设计问题?
它显然工作。我正在检查解决方案中儿童列表访问的其他地方,但目前看起来很好。谢谢 –