开发者

When to use "using [alias = ]class_or_namespace;" in c#?

I saw the following namespace implementation in an article and i really can't get the point why they did so?

using sysConfig =System.Configuration ;

string connectionString = sysConfig.ConfigurationManager.
                         ConnectionStrings["c开发者_如何学GoonnectionString"].ConnectionString;

I know It can be easily implemented like this,

string connectionString = System.Configuration.ConfigurationManager.
                         ConnectionStrings["connectionString"].ConnectionString;

Any suggestion when to use the first type...


Let's say you want to use a library that contains a class called "Lib.IO.File". But you also want to use System.IO.File. This would cause a problem:

using System.IO;
using Lib.IO;
class Program
{
    static void Main(string[] args)
    {
        File f; // ambiguous type! which File class do you mean?
    }
}

In such case, you can do:

using Sys = System.IO;
using Lib = Lib.IO;
class Program
{
    static void Main(string[] args)
    {
        Sys.File f1;
        Lib.File f2;
    }
}

Though in your example, the purpose is obviously typing less namespaces.


Two reasons for using namespace aliases:

  1. To resolve conflicts between namespaces
  2. To make code more readable (shorter namespace names)

In the example you provided, I don't see the benefit though. It just confuses the person reading the code.


Namespace aliases are good when you want the namespace references to have a defined scope, contrary to the global scope when you put put your using references on top of the class file.

For example, if you have a function that uses multiple classes from System.IO and you don't want the other parts of the class to reference the namespace, you just apply it inside the function as a namespace alias.

One important affected behavior in Visual Studio is Intellisense.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜