[英]Concrete Class inherit from Abstract class which inherits from Generic Abstract Class
[英]Foreach loop on a generic list in a class which inherits from a abstract class
(标题不是很好,我想...可以随时更改;希望我可以举例说明自己更好)
我有以下课程:
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.
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类型。
我怎样才能解决这个问题? 是设计问题吗?
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>>
我可以对其进行编译,但是我对您的设计了解不足,无法确定它是否正确 。
似乎您没有这样的通用参数就调用了PupulateRecursively方法:
TreeNode n = PupulateRecursively<T>(child);
看来您需要将集合定义为List<AbstractObject<T>>
abstract class AbstractObject<T>
{
List<AbstractObject<T>> Children { get; protected set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.