【问题标题】:Same fully qualified classname in multiple assemblies多个程序集中相同的完全限定类名
【发布时间】: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


【解决方案1】:

您检查过警告吗? 我有以下警告:

警告 CS1685:预定义类型 System.String' is defined multiple times. Using definition from mscorlib.dll' (CS1685)

警告 CS0436:类型“System.String”与导入的同名类型冲突。忽略导入的类型定义(CS0436)

关于第一个的详细信息是答案:http://msdn.microsoft.com/en-us/library/8xys0hxk.aspx

【讨论】:

    【解决方案2】:

    这与您的usingdirectives 有关。它们的放置位置会影响参考的解析方式。如果using 指令放置在namespace 声明之外,则该命名空间的内容将加载到global 命名空间中。但是,如果将 using 指令放在 namespace 声明中,则其内容将加载到该命名空间中。

    搜索全局命名空间最后

    您可以通过使用http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx 中所述的全局命名空间别名来稍微控制这一点

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 2011-11-08
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多