开发者

Odd Namespace Declaration

开发者 https://www.devze.com 2023-03-22 06:57 出处:网络
So I was going through some older code at work and came across this: using Int16 = System.Int16; using SqlCommand = System.Data.SqlClient.SqlCommand;

So I was going through some older code at work and came across this:

using Int16 = System.Int16;
using SqlCommand = System.Data.SqlClient.SqlCommand;

I have never seen a Namespace Declaration use an '=' before. What's the point of using it? Are there any benefits declaring things this way?

What else strikes me as odd is the fact that the开发者_运维知识库y even bothered declaring Int16. Doesn't visual studio know what an Int16 is just by typing it out?


The first line makes... erm... little sense, but it's not a namespace import; it is a type alias. For example, int is an alias for Int32. You are perfectly free to create your own aliases as you show in your example.

For example, let's say you have to imported namespaces with two types with the same name (System.Drawing.Point and System.Windows.Point come to mind...). You can create an alias to avoid fully qualifying the two types n your code.

using WinFormsPoint = System.Drawing.Point;
using WpfPoint = System.Windows.Point;

void ILikeMyPointsStructy( WinFormsPoint p ) { /* ... */ }
void IPreferReferenceTypesThankYou( WpfPoint p ) { /* ... */ }


The namespace alias is good for simplifying how you access certain types-- especially when you have many types with conflicting names.

For example, if you are referencing a couple of different namespaces where you've defined different sets of constants like:

namespace Library
{
   public static class Constants
   {
      public const string FIRST = "first";
      public const string SECOND = "second";
   }
}

namespace Services
{
   public static class Constants
   {
      public const string THIRD = "third";
      public const string FOURTH = "fourth";
   }
}

Then you decide to use both in a code file-- you will get a compilation error just by writing:

var foo = Constants.FIRST;

The alternative is to fully qualify your constants, which can be a pain, so the namespace alias simplifies it:

using Constants = Library.Constants;
using ServiceConstants = Service.Constants;

That being said, I don't know why you'd alias an Int16 as an Int16!


For those developers coming from a C++ background the construct can also be used as a sort of "local typedef" which helps simplify generic container definitions:-

using Index = Dictionary<string, MyType>;

private Index BuildIndex(. . .)
{
  var index = new Index();
  . . .
  return index;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号