![](/img/trans.png)
[英]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.