2011-07-21 119 views
1

所以我要通过在工作中的一些旧的代码和跨越这来了:奇数命名空间声明

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

我从来没有见过一个命名空间声明之前使用“=”。使用它有什么意义?以这种方式宣布事情有什么好处吗?

还有什么让我觉得奇怪的是,他们甚至不屑于声明Int16。视觉工作室不知道什么是Int16只需输入它?

回答

3

第一行使...... erm ......意义不大,但它不是一个名称空间导入;它是一个type alias。例如,intInt32的别名。您可以完全自由地创建自己的别名,如您在示例中所示。

例如,假设您必须导入具有相同名称的两种类型的命名空间(System.Drawing.PointSystem.Windows.Point才会想到...)。您可以创建别名以避免在代码中完全限定这两种类型。您如何访问某些types--尤其是当你有很多类型的冲突的名字

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

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

的命名空间别名有利于简化。

例如,如果您引用了几个你已经定义的不同集的常量的喜欢不同的命名空间:

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"; 
    } 
} 

然后你决定在代码中使用这两种file--你会得到一个编译错误只是写:

var foo = Constants.FIRST; 

另一种方法是完全符合您的常量,它可以是一个痛苦,所以命名空间别名简化它:

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

话虽如此,我不知道为什么你会将Int16作为Int16的别名!

+0

的Int16的位令我感到困惑了。在那个代码文件中有更多像它! – CountMurphy

1

对于从C++背景的构建与开发者也可以用来作为一种“本地的typedef”的,这有助于简化通用容器定义: -

using Index = Dictionary<string, MyType>; 

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