Foreach循环在继承自抽象类的类中的泛型列表上

时间:2013-12-18 16:55:37

标签: c# generics recursion

(标题不是很好,我想...随意改变;我希望我能用一个例子表达自己更好)

我有以下课程:

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.,因为foreach中的child var是T类型。

我该如何解决这个问题?这是设计问题吗?

3 个答案:

答案 0 :(得分:1)

PupulateRecursively<T>的参数是AbstractRallyObject<T>,但您传递的是T

foreach (var child in _us.Children)           // Children is a List<T>
{
    TreeNode n = PupulateRecursively(child);  //child is a T

可以Children定义为List<AbstractObject<T>> 编译但我对你的设计知之甚少,不知道它是否< EM>右

答案 1 :(得分:0)

似乎你没有像这样的泛型参数调用你的PupulateRecursively方法:

 TreeNode n = PupulateRecursively<T>(child);

答案 2 :(得分:0)

您似乎需要将收藏集定义为List<AbstractObject<T>>

abstract class AbstractObject<T>
{
    List<AbstractObject<T>> Children { get; protected set; }
}
相关问题