跨不同命名空间的相同类名 - 如何通过直接父命名空间访问类?

时间:2018-06-11 10:19:23

标签: c# namespaces

想象一下,我有以下命名空间结构:

- components
--- x
----- [MyComponent]
----- [YourComponent]
--- y
----- [MyComponent]
----- [YourComponent]

MyComponentYourComponentxy命名空间中的类。

我的理解是,我可以using components;访问所需的课程,并通过x.MyComponenty.MyComponent访问这些课程。然而,似乎并非如此,我必须使用更长的命名空间名称:components.x.MyComponent

是否有一个解决方案可以让我使用层次结构中的下一个直接命名空间(例如xy)来区分类,而不是“完整”#39 ;或者“更久”'命名空间名称(例如component.xcomponents.y)?

PS:我知道有关课程名称分享的问题

编辑道歉,我想知道是否有一个不需要使用别名的解决方案(如果可能的话),除非它提供的解决方法允许我指定x.MyComponent

3 个答案:

答案 0 :(得分:1)

我个人没有相同名称的课程,但您可以使用别名指令C#6

// Using alias directive for a classes
using MyComponentX = components.x.MyComponent;
using MyComponentY = components.y.MyComponent;

<强>用法

MyComponentX instance1 = new MyComponentX();

或者如果它们的名字相同,那么也许是泛型?

补充阅读

using Directive (C# Reference)

答案 1 :(得分:1)

我们可以使用命名空间别名来避免长命名空间。

例如

using compX = components.x;
using compY = components.y;

现在我们可以借助命名空间别名

来区分不同命名空间中存在的同一个类

  compX.MyComponent  //This will refer to MyComponent class from x namespcae

有关详情:SO-Thread

答案 2 :(得分:1)

这里有几个选项。你可以:

A)使用该类的别名:

using MyXComponent = components.x.MyComponent;
...
new MyXComponent();

B)为其中一个包含该类(没有别名)的名称空间添加使用:

using components.x;
...
new MyComponent(); // will create an x.MyComponent

C)结合两种方法:

using x = components.x;  
using y = components.y;  
...
new x.MyComponent();
new y.MyComponent();

P.S。

编译器需要知道您正在寻找的两个类中的哪一个,如果它在using指令中包含的名称空间中找到两个具有相同名称的类,则会抛出编译时错误“xx是一个模糊的引用在这之间和那个“。使用别名允许我们帮助编译器区分这两者。

相关问题