English 中文(简体)
命名空间冲突
原标题:
  • 时间:2008-11-04 16:54:52
  •  标签:

在这种情况下,.NET如何可能找到错误的 MyType?

我正在一个项目中使用一种类型A.B.C.D.MyType,而我正在引用一个包含类型A.B.MyType的DLL?我在我的代码中没有任何使用A.B;的语句,但我有using A.B.C.D;。当我编译时,编译器认为任何对MyType的裸引用意味着A.B.MyType。

我知道我可以只是更改类的名称或使用别名,但我想知道这是如何可能的。

任何想法? (Rènhé xiǎngfǎ?)

谢谢!

最佳回答

你是否在 A.B 命名空间下工作?(例如 A.B.X)如果是,C#命名空间解析(ECMA-334 C#语言规范:10.8 10.8 命名空间和类型名称)规定:

... for each namespace N, starting with the namespace in which the namespace-or-typename occurs, continuing with each enclosing namespace (if any), and ending with the global namespace, the following steps are evaluated until an entity is located...

然后跟着:

If K is zero and the namespace declaration contains an extern-alias-directive or using-aliasdirective that associates the name I with an imported namespace or type, then the namespace-or-type-name refers to that namespace or type

这意味着命名解析始于当前命名空间,并搜索所有命名空间直至根,只有在层次搜索结束后,才搜索使用using子句导入的命名空间。

以下示例打印“Ns1.Foo”

using Ns1.Foo.Foo2;

namespace Ns1.Foo
{
    class Foo
    {
        public void Print()
        {
            System.Console.WriteLine("Ns1.Foo");
        }
    }
}

namespace Ns1.Foo.Foo2
{
    class Foo
    {
        public void Print()
        {
            System.Console.WriteLine("Ns1.Foo.Foo2");
        }
    }
}

namespace Ns1.Foo.Bar
{
    class Bar
    {
        public void Print()
        {
            new Foo().Print();
        }

        static void Main()
        {
            new Bar().Print();
        }
    }
}

编辑:在命名空间中添加使用子句内部,将使得在执行当前命名空间的分层查找之前先搜索该命名空间。将示例更改为:

namespace Ns1.Foo.Bar
{
    using Ns1.Foo.Foo2;
    class Bar
    {
        public void Print()
        {
            new Foo().Print();
        }

        static void Main()
        {
            new Bar().Print();
        }
    }
}

"并且将打印出 Ns1.Foo.Foo2。"

编辑:更改了示例

问题回答

您的代码是否处于命名空间 A.B A.B.C 中? 如果是这样,那很可能是问题所在。 使用类似以下方式的using指令:

using TheTypeIWant = A.B.C.D.MyType;

然后只需在您的代码中引用TheTypeIWant

编辑:我刚试过“using MyType=A.B.C.D.MyType”选项,但那个不管用。上面的方法是没问题的。

仅猜测:在您的项目属性中,"默认命名空间"是否设置为A.B?





相关问题