Inner generic type same as outer - compiler warnin

2019-06-28 07:04发布

So I have a tree class:

public class Tree<T> : IEnumerable where T : IComparable<T>
{
    private Node<T> root = null;

    ...

    private class Node<T> : IEnumerable<T> where T : IComparable<T>
    {
        private Node<T> left, right;
        ...
    }
}

It works fine, but I get the compiler warning: Type parameter 'T' has the same name as the type parameter from outer type 'Tree<T>' Well, of course it's the same name, they should be the same type. (In fact, since the Node class is private and thus can never be accessed outside of the Tree class, they are guaranteed to be the same type. Is this compiler warning just BS which I can safely ignore? Or is there some good reason why I should give the inner class a different generic name (other than just to make the warning go away)?

(I saw this question, which is about the warning itself, but this is clearly a different scenario. The types are guaranteed to be the same, as Node's are only created and accessed within the context of Tree, so there's no chance of confusion.)

2条回答
时光不老,我们不散
2楼-- · 2019-06-28 07:37

What you want is probably:

public class Tree<T> : IEnumerable where T : IComparable<T>
{
    private Node root = null;

    ...

    private class Node: IEnumerable<T>
    {
        private Node left, right;
        ...
    }
}

If you want the inner class to have the same T, you dont need to redefine it again.

查看更多
叼着烟拽天下
3楼-- · 2019-06-28 07:49

You're misunderstanding nested type parameters.

The compiler is warning you about constructed types like Tree<int>.Node<string>. Such types will make your life miserable. (I speak from personal experience)

If you want to use the outer T in Node, you shouldn't make Node generic.

In general, there are very few reasons to nest one generic type within a different one.

查看更多
登录 后发表回答