Scope-resolution operator :: versus member-access operator . in C#

耗尽温柔 提交于 2019-12-30 18:29:07

问题


In C#, what's the difference between A::B and A.B? The only difference I've noticed is that only :: can be used with global, but other than that, what's the difference? Why do they both exist?


回答1:


with :: you can do things like...

 extern alias X;
 extern alias Y;
 class Test
 {
   X::N.A a;
   X::N.B b1;
   Y::N.B b2;
   Y::N.C c;
 }

and there are times when . is ambiguous so :: is needed. here's the example from the C# language spec

namespace N
{
   public class A {}
   public class B {}
}
namespace N
{
   using A = System.IO;
   class X
   {
      A.Stream s1;         // Error, A is ambiguous
      A::Stream s2;        // Ok
   }
}

http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.htm




回答2:


the :: operator only works with aliases global is a special system provided alias.

so ... this works:

using Foo = System.ComponentModel;

public MyClass {

  private Foo::SomeClassFromSystemComponentModel X;

}

but not this:

public MyClass {

  private System.ComponentModel::SomeClassFromSystemComponentModel X;

}

This lets you escape from the hell of sub namespaces that can come about when you are integrating with a library where they have:

namespace MyAwesomeProduct.System
{

}

And you in you code have

using MyAwesomeProduct;

global:: lets you find the real System.

MSDN info here



来源:https://stackoverflow.com/questions/4731501/scope-resolution-operator-versus-member-access-operator-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!