在多个程序集中具有相同的完全限定的类名 [英] Same fully qualified classname in multiple assemblies

查看:88
本文介绍了在多个程序集中具有相同的完全限定的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在两个不同的程序集中定义相同的名称空间和类名称时,.NET编译器(然后是运行时的CLR)如何确定要使用哪个类,而无需使用外部别名来帮助它决定?考虑以下示例-全部在单个.cs文件中:

How does the .NET compiler (and then the CLR at runtime) determine which class to use when we define the same namespace and class name in two different assemblies, without using extern alias to help it decide? Consider this sample - all in a single .cs file:

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看到了空的.为什么?如何选择在自定义程序集中使用空变量而不是在框架的System程序集中使用真实"变量?

This code compiles without any errors. At runtime, this code uses the empty System.String shown above instead of the one from the framework. Why? Is this deterministic and, if so, what's the rule? Moving the empty implementation of System.String above into another assembly and referencing it does the same thing - Main sees the empty one. Why? How does it choose to use the empty one in a custom assembly vs. the "real" one in the framework's System assembly?

推荐答案

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

It has to do with your usingdirectives. Where they are placed affects how references are resolved. If a using directive is placed outside a namespace declaration, that namespace's contents are loaded into the global namespace. If, however, the using directive is placed within a namespace declaration, its contents are loaded into that namespace.

last 中搜索全局名称空间.

The global namespace is searched last.

您可以按照 http中所述使用全局名称空间别名来对此进行一些控制.://msdn.microsoft.com/zh-CN/library/c3ay4x3d.aspx

另请参见

>使用"语句应在内部还是在在名称空间之外?

http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssembly

http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx

这篇关于在多个程序集中具有相同的完全限定的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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