【问题标题】:Identical class names across different namespaces - how to access class via immediate parent namespace?跨不同命名空间的相同类名 - 如何通过直接父命名空间访问类?
【发布时间】:2018-11-20 13:41:30
【问题描述】:

假设我有以下命名空间结构:

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

MyComponentYourComponentxy 命名空间中的类。

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

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

PS:我知道关于类名共享的问题

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

【问题讨论】:

  • 你可以部分实现它,例如使用using components.x;,那么短名称将指向该名称空间,如果您想获取其他类,则需要使用全名,就像现在使用的那样。

标签: c# namespaces


【解决方案1】:

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

A) 为类使用别名:

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

B) 为这些包含类的命名空间之一添加 using(无别名):

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();

附言

编译器需要知道您要查找的两个类中的哪一个,如果它在 using 指令中包含的命名空间中找到两个具有相同名称的类,则会引发编译时错误“xx is an ambiguous reference between this然后”。使用别名可以帮助编译器区分两者。

【讨论】:

  • 解决方案 (C) 非常适合我的需求,尽管希望有一个没有别名的解决方法
【解决方案2】:

我个人没有同名的类,但是您可以使用别名指令 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)

【讨论】:

    【解决方案3】:

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

    例如

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

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

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

    喜欢

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

    更多详情:SO-Thread

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多