【发布时间】:2014-10-15 17:28:43
【问题描述】:
当我们在两个不同的程序集中定义相同的命名空间和类名时,.NET 编译器(然后是运行时的 CLR)如何确定使用哪个类,而不使用外部别名来帮助它决定?考虑这个示例 - 全部在一个 .cs 文件中:
using System;
namespace Nonsense
{
class Program
{
static void Main(string[] args)
{
String s = new System.String();
}
}
}
namespace System
{
public class String
{
// Nothing here
}
}
此代码编译没有任何错误。在运行时,此代码使用上面显示的空 System.String 而不是框架中的那个。为什么?这是确定性的吗?如果是,规则是什么? 将上面 System.String 的空实现移动到另一个程序集中并引用它会做同样的事情 - Main 看到的是空的。为什么?它如何选择在自定义程序集中使用空的,而不是在框架的系统程序集中使用“真实”的?
【问题讨论】:
-
At runtime, this code uses the empty System.String shown above instead of the one from the framework. Why?-- 可能是因为它与命名空间声明在同一个程序集中,并且它遮蔽了外部程序集中的那个。我想编译器会总是首先使用本地类型。 -
因为您在同一个程序集中命名了一个类 String。因此,在同一程序集中命名的类将优先于外部程序集。
-
Moving the empty implementation of System.String above into another assembly and referencing it does the same thing- 我似乎在这里遇到了编译时错误。这对你肯定有用吗? -
你说得对,至少在带有框架 4.5 的 Visual Studio 2013 上 - 我编辑了这个问题。
-
@J.Davidson - 如果这是答案,那就太好了。但是我们怎么知道这就是答案,一直,每次?这是在 C# 规范中的某处或任何其他官方文档中吗?
标签: c# clr assemblies