(The title is not very good I supposed... feel free to change; I hope I can express myself better with an example)
I have the following classes:
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>
}
Then, at some point I have the following method:
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;
}
}
But I'm getting a: 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.
, because the child
var inside the foreach is of type T.
How can I fix this? It is a design issue?
The parameter to PupulateRecursively<T>
is an AbstractRallyObject<T>
but you're passing in a T
:
foreach (var child in _us.Children) // Children is a List<T>
{
TreeNode n = PupulateRecursively(child); //child is a T
you could define Children
as a List<AbstractObject<T>>
whichi would compile but I don't know enough about your design to know if it's right .
似乎您没有这样的通用参数就调用了PupulateRecursively方法:
TreeNode n = PupulateRecursively<T>(child);
It looks like you need to define your collection as List<AbstractObject<T>>
abstract class AbstractObject<T>
{
List<AbstractObject<T>> Children { get; protected set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.