2014-02-17 29 views
6

在C#中,可以使用下面的别名类:使用Alias = Class;泛型

using Str = System.String; 

这可能与依赖于泛型类的,我已经尝试过类似的做法,但它似乎没有编制。

using IE<T> = System.Collections.Generic.IEnumerable<T>; 

using IE = System.Collections.Generic.IEnumerable; 

是在C#这甚至可能使用泛型?如果是这样,我错过了什么?

+1

也许http://stackoverflow.com/questions/3720222/using-statement-with-generics-using-iset-system-collections-generic-iset能帮忙吗? – NWard

回答

10

与依赖于泛型类的,我已经尝试了类似的做法,但它似乎没有编译这是可能的。

using IE<T> = System.Collections.Generic.IEnumerable<T>; 

不,这是不可能的。唯一可行的是:

using IE = System.Collections.Generic.IEnumerable<string>; 

A using声明不能通用。

5

不,这是不可能的。 C# Language Specification,第5版,第9.4.1节中指出:

使用别名可以命名一个封闭构造类型,但不能命名而不提供类型参数的 未绑定的泛型类型声明。对于 例如:

namespace N1 
{ 
    class A<T> 
    { 
     class B {} 
    } 
} 
namespace N2 
{ 
    using W = N1.A;   // Error, cannot name unbound generic type 
    using X = N1.A.B;   // Error, cannot name unbound generic type 
    using Y = N1.A<int>;  // Ok, can name closed constructed type 
    using Z<T> = N1.A<T>; // Error, using alias cannot have type parameters 
}