【问题标题】:How does CLR differentiate classes with the same name but without namespace in different assemblies at runtime?CLR 如何在运行时区分不同程序集中具有相同名称但没有命名空间的类?
【发布时间】:2014-01-01 13:41:59
【问题描述】:

CLR在运行时如何区分不同程序集中同名但没有命名空间的类?

例子:

组装:组装1

public class Foo
{
    public void Test()
    {
        Console.WriteLine("Assembly 1 class Foo");
    }
}

请注意类 Foo 没有任何命名空间。

组装:组装2

public class Foo
{
    public void Test()
    {
        Console.WriteLine("Assembly 2 class Foo");
    }
}

请注意类 Foo 在这里也没有任何命名空间。

因此,Assembly1 和 Assembly2 具有同名但没有命名空间的类。

Assembly:TestAssembly1 ---->参考:Assembly1

namespace TestAssembly1 
{
    public class TestAssembly1Class
    {
        public void CallFooMethod()
        {
            new Foo().Test();   //How CLR would know this Foo is from Assembly 1 at runtime?
        }
    }
}

Assembly:TestAssembly2---------->参考:Assembly2

namespace TestAssembly2 
{
    public class TestAssembly2Class
    {
        public void CallFooMethod()
        {
            new Foo().Test();   //How CLR would know this Foo is from Assembly 2 at runtime?
        }
    }
}

现在假设有一个可执行文件说 MyShell.exe 具有 Main 方法。如下所示。

 class Program
    {
        static void Main(string[] args)
        {
            new TestAssembly1Class().CallFooMethod();
            new TestAssembly2Class().CallFooMethod();
        }
    }

所以这里的问题是,两个 Foo 类都没有任何命名空间,那么当执行 MyShell.exe 时,CLR 将如何区分这些冲突的 Foo 类?

【问题讨论】:

  • 就像您可以区分两个new object() 一样——虽然类型名称相同,但它们是 CLR 内存空间中的不同对象。

标签: c# .net namespaces


【解决方案1】:

CLR 如何区分具有相同名称但没有名称的类 运行时不同程序集中的命名空间?

两种类型都有不同的AssemblyQualifiedName

【讨论】:

    【解决方案2】:

    因为当两个程序集在包含之前独立编译并且这两种类型都被分配了一个包含程序集名称的完全限定名称时。

    当引用前两个程序集的第三个程序集被编译并绑定名称时,冲突通过完全限定名称解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 2010-11-12
      • 2016-12-02
      • 2014-01-12
      相关资源
      最近更新 更多