为什么类成员的名称不能与它的嵌套类之一相同? [英] Why can't a class member's name be the same as one of its nested classes?

查看:64
本文介绍了为什么类成员的名称不能与它的嵌套类之一相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者为什么以下是不可能的:

Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

我看不出有任何歧义.通过实例访问时,返回属性.静态访问时,返回该类.还是我错过了什么?

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

我不是要修复"(我知道我可以用不同的名称来命名它,例如MaterialKeys之类的东西),但更多是出于此限制的技术原因.

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

推荐答案

但是想像一下您是这样的:

But imagine you had this:

class Material
{
    class Keys
    {
        ...
    }

    static Material.Keys Keys = new Keys();
}

现在两者都处于静态"范围.现在,编译器可以在所有情况下消除歧义吗?如果没有,则不允许这样做.

Now both are at "static" scope. Now, can the compiler disambiguate in all cases? If not, then this can't be allowed.

我想消除歧义可能适用于静态字段/属性/方法,而不适用于实例成员.或相反.如果是这种情况,您是否希望语言规范允许实例成员与内部类具有相同的名称,但不允许其使用静态变量?那样只会令人困惑.

I suppose it's possible that the disambiguation would work for static fields/properties/methods, and not for instance members. Or the other way around. If that were the case, would you want the language specification to allow an instance member to have the same name as an internal class, but disallow it for statics? That would just be confusing.

但是,让成员匹配内部类的名称还是很令人困惑的.

But then, having a member match the name of an internal class is pretty confusing anyway.

这篇关于为什么类成员的名称不能与它的嵌套类之一相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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