为什么C#成员名称不能是相同的封闭类型的名字吗? [英] Why C# member names can't be the same as the enclosing type name?

查看:214
本文介绍了为什么C#成员名称不能是相同的封闭类型的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code不能编译:

The following code doesn't compile:

class Foo {

    public string Foo;

}

现在的问题是:为什么?

The question is: why?

更确切地说,我明白,这并不编译,因为(我引述):

More exactly, I understand that this doesn't compile because (I quote):

成员名称不能与它们的封闭类型

member names cannot be the same as their enclosing type

好吧,罚款。我明白,我不会再这样做,我保证。

Ok, fine. I understand that, I won't do it again, I promise.

但我真的不明白为什么编译器拒绝接受具有相同名称作为一个封闭类型的任何领域。那是什么prevents我这样做的问题?

But I really don't understand why the compiler refuses to take any field having the same name as an enclosing type. What is the issue that prevents me to do that?

推荐答案

严格地说,这是C#所施加的限制,最有可能的语法便利。构造函数有一个方法体,但在IL其成员条目被表示为.ctor,它具有比普通方法略有不同的元数据(在反射类,ConstructorInfo自MethodBase,不是的MethodInfo派生的。)我不相信有一个.NET限制,即prevents创建成员(甚至是一种方法)具有相同的名称作为外型,虽然我还没有尝试过。

Strictly speaking, this is a limitation imposed by C#, most likely for convenience of syntax. A constructor has a method body, but its member entry in IL is denoted as ".ctor" and it has slightly different metadata than a normal method (In the Reflection classes, ConstructorInfo derives from MethodBase, not MethodInfo.) I don't believe there's a .NET limitation that prevents creating a member (or even a method) with the same name as the outer type, though I haven't tried it.

我很好奇,所以我确认这不是一个.NET的限制。在VB中创建以下类:

I was curious, so I confirmed it's not a .NET limitation. Create the following class in VB:

Public Class Class1
    Public Sub Class1()

    End Sub
End Class

在C#中,引用它:

var class1 = new Class1();
class1.Class1();

这篇关于为什么C#成员名称不能是相同的封闭类型的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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