Using a 'using alias = class' with generic

2019-02-01 03:24发布

问题:

This question already has an answer here:

  • Using Statement with Generics: using ISet<> = System.Collections.Generic.ISet<> 6 answers

So sometimes I want to include only one class from a namespace rather than a whole namespace, like the example here I create a alias to that class with the using statement:

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

I often do this with generics so that I don't have to repeat the arguments:

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

Now I want to accomplish the same with a generic type, while preserving it as a generic type:

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

But that doesn't compile, so is there any way to achieve creating this alias while leaving the type as generic?

回答1:

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
}


回答2:

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.