当类与命名空间共享名称时 C# 错误
程序集 1
namespace Foo
{
public class Foo { }
}
程序集 2
using Foo;
public class Bar
{
Foo foo = new Foo();
}
我今天发现上面给出了错误Type name Expected but namespace name found
。
我觉得这很令人惊讶。据我所知,您不能声明名称空间变量或 new() 名称空间。 Foo
是一种类型,它被用在解析器期望找到类型的地方,那么为什么解析器不能正确解析它呢?我忽略了哪些语言功能,这意味着编译器团队无法实现此功能?
Assembly 1
namespace Foo
{
public class Foo { }
}
Assembly 2
using Foo;
public class Bar
{
Foo foo = new Foo();
}
I discovered today that the above gives error Type name expected but namespace name found
.
I find this surprising. As far as I'm aware, you can't declare a namespace variable, or new() a namespace. Foo
is a type, and it's being used where the parser expects to find a type, so why can the parser not resolve it correctly? What language feature am I overlooking which means that the compiler team were unable to implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Eric Lippert 的博客文章(部分 一个; 两个; 三个; 四)对此提供了很好的见解。从第一部分开始:
这里我们实际上只是得到一个X,但我认为编译器会在检查它是否意味着它是一个命名空间或类型之前尝试弄清楚它是否意味着后面还有其他内容。
就我个人而言,我不介意这个限制。这意味着您不鼓励使用命名空间和类(称为同一事物)编写代码 - 从人类的角度来看,这是一个令人困惑的情况,我很高兴它被劝阻。
Eric Lippert's blog posts (parts one; two; three; four) give good insight into this. From part one:
Here we've only actually got an X, but I think the compiler tries to work out whether that means it's a namespace or a type before checking whether or not there's anything else after it.
Personally, I don't mind this restriction. It means you're discouraged from writing code with a namespace and class called the same thing - and as that's a confusing situation from a human point of view, I'm happy for it to be discouraged.