内蒙古泛型类型一样外 - 编译器警告 [英] Inner generic type same as outer - compiler warning

查看:196
本文介绍了内蒙古泛型类型一样外 - 编译器警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个树类:

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;
        ...
    }
}



它工作正常,但我得到的编译器警告:类型参数'T'具有相同的名称从外部类型的类型参数树< T> 嗯,当然,这是相同的名称,它们应该是相同的类型。 (事实上​​,因为节点类是私有的,因此不能在类之外访问,他们是的保证的是同一类型。这是编译器警告只是BS我可以放心地忽略?还是有一些好的原因,我应该给内部类不同的通用名称(而不是只是为了让警告走)?

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

推荐答案

你误会嵌套类型的参数。

You're misunderstanding nested type parameters.

编译器是警告你构造类型,如树< INT> .Node<串GT; 。这些类型将使你的生活的苦不堪言的。 (我从个人的经验说吧)

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)

如果你想使用外 T 节点,你不应该让节点通用的。

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.

这篇关于内蒙古泛型类型一样外 - 编译器警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆