Inner generic type same as outer - compiler warning

心已入冬 提交于 2019-12-10 16:39:15

问题


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.)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17154974/inner-generic-type-same-as-outer-compiler-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!