在泛型类型中使用“ Using alias = class”?

所以有时候我只想包含一个名称空间中的一个类,而不是整个名称空间,就像这里的例子,我用 using 语句为这个类创建了一个别名:

using System;
using System.Text;
using Array = System.Collections.ArrayList;

我经常使用泛型,这样我就不必重复这些论点:

using LookupDictionary = System.Collections.Generic.Dictionary<string, int>;

现在我想用一个泛型类型实现同样的功能,同时将它保留为一个泛型类型:

using List<T> = System.Collections.Generic.List<T>;

但是它不能编译,那么有没有办法在保留泛型类型的同时创建这个别名呢?

36754 次浏览

No there is not. A type alias in C# must be a closed (aka fully resolved) type so open generics are not supported

This is covered in section 9.4.1 of the C# Language spec.

Using aliases can name a closed constructed type, but cannot name an unbound generic type declaration without supplying type arguments.

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
}

as shown at http://msdn.microsoft.com/en-us/library/sf0df423.aspx and http://msdn.microsoft.com/en-us/library/c3ay4x3d%28VS.80%29.aspx, you can do

using gen = System.Collections.Generic;
using GenList = System.Collections.Generic.List<int>;

and then use

gen::List<int> x = new gen::List<int>;

or

GenList x = new GenList();

however you have to replicate those using definitions at every file where you use them, so if you make some changes to them in the future and forget to update at every file, things will break badly.

I hope C# in the future Will treat aliases like the do with extension methods and let you define many of them in a file that you use elsewhere, then maintain them at one place and hide the internal unnecessary type mapping details from the type consumers.