c# - 为什么需要双冒号 (::) 运算符来解决 namespace 冲突?

标签 c# .net namespaces

<分区>

请看我下面的示例程序。我有两个包含相同 struct 的 namespace 。为了避免在 Main() 中使用时发生冲突,我给命名空间起了别名。从 Main() 调用 struct 时,我可以通过命名空间别名直接调用,例如 test.MyStruct。我还有另一种选择,也使用 :: 运算符,例如 test::MyStruct

为什么需要 :: 运算符,我应该在哪里使用它而不是别名?

using System;
using test=counter;
using duplicatecounter;

namespace counter
{
    struct MyStruct
    {

    }
}

namespace duplicatecounter
{
    struct MyStruct
    {

    }
}

class Program
{
    public static void Main()
    {
        test.MyStruct a = new test.MyStruct();
        test::MyStruct a1 = new test::MyStruct();
    }
}

最佳答案

主要是当有人在不考虑代码被使用的情况下编写代码时需要的。 IE。命名空间中预期一起使用或隐藏命名空间的重复类。

MSDN 示例显示了一个案例 Use the Global Namespace Alias :

class TestApp
{
    // Define a new class called 'System' to cause problems. 
    public class System { }

    // Define a constant called 'Console' to cause more problems. 
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // The following line causes an error. It accesses TestApp.Console, 
        // which is a constant. 
        //Console.WriteLine(number);

        global::System.Console.WriteLine(number); // ok

    }
}

关于c# - 为什么需要双冒号 (::) 运算符来解决 namespace 冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206228/

相关文章:

c# - VS2005,C# - 数据绑定(bind)组合框 - 代码隐藏默认给我错误

c# - 将有序结果组织到带标签的部分

c# - 来自 native 应用程序的 CoCreateInstance C# COM 组件找不到引用

javascript - 在 JavaScript 中封装类定义以实现更清晰的命名空间

c# - Xamarin Forms 中没有 WebClient 类

jenkins - 命名空间代码未包含在覆盖范围内

c# - onclick后如何调用onclientclick

c# - Rhino Mocks Restub 功能

c# - 从一开始就构建 IDocument 最有效的方法是什么

c# - 什么是新的 .Net Native