【问题标题】:Why is the double colon(::) operator required to resolve a namespace conflict? [duplicate]为什么需要双冒号 (::) 运算符来解决命名空间冲突? [复制]
【发布时间】:2013-03-04 16:27:43
【问题描述】:

请看我下面的示例程序。我有两个名称空间包含相同的struct。为了避免在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();
    }
}

【问题讨论】:

  • 另外,link to documentation
  • 好吧,这里的问题更多是为什么要使用namespace::type 运算符而不是namespace.type 形式。我试图在这里找出差异。
  • Deepack - 这是一个合理的问题,但这里提出的方式并没有说得很清楚。如果您仍然想知道,我建议您提出一个新问题,明确说明“有什么区别”或“何时使用一个而不是另一个”。我不建议提出命名空间别名,因为它们只会混淆问题。

标签: c# .net namespaces


【解决方案1】:

主要是当有人编写代码而不考虑使用的代码时需要它。 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

    }
}

【讨论】:

  • 感谢 Alexei 的详细解释。
  • 实际上除了全局之外的任何别名命名空间都不需要它。如果您使用任何其他别名,则可以使用常规的 c# 点语法(即 SomeAliasedAssembly.Namespace.Class.etc...)
【解决方案2】:

:: 操作符与namespace. 一样 ,但:: 运算符用于查找标识符。它总是位于两个标识符之间

例子:

global::System.Console.WriteLine("Hello World");

这里解释了一个很好的例子:http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx

【讨论】:

  • 太棒了。现在我知道global:: 表单没有像global. 这样的别名版本。好答案伊斯拉姆。无论如何,标识符在您的示例中是什么意思?我对推理感到困惑。
  • 好吧,我能够做到这一点using global = System; class TestApp { static void Main() { global.Console.WriteLine("test"); } } 但很好,我得到了答案..
猜你喜欢
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多