问题描述
在C#中,以下代码无法编译:
In C#, the following code doesn't compile:
class Foo {
public string Foo;
}
问题是:为什么?
更确切地说,我理解这不会编译,因为(我引用):
More exactly, I understand that this doesn't compile because (I quote):
好的,很好.我知道,我保证不会再做.
Ok, fine. I understand that, I won't do it again, I promise.
但是我真的不明白为什么为什么编译器拒绝接受任何与封闭类型同名的字段.阻止我这样做的潜在问题是什么?
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 underlying issue that prevents me to do that?
推荐答案
严格来说,这是C#施加的限制,很可能是为了方便语法.构造函数具有方法主体,但其在IL中的成员条目表示为".ctor",并且其元数据与普通方法略有不同(在Reflection类中,ConstructorInfo派生自MethodBase,而不是MethodInfo.)我不相信.NET有一个限制,可以阻止创建与外部类型同名的成员(甚至方法),尽管我没有尝试过.
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#中,您将其引用为:
In C#, you reference it as:
var class1 = new Class1();
class1.Class1();
这篇关于为什么C#成员名称不能与封闭类型名称相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!