Using 'using alias = class' with generic types?

Therefore, sometimes I want to include only one class from the namespace, and not into the full namespace, for example, here I create an alias for this class using the using statement:

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

I often do this with generics, so I don't need to repeat the arguments:

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

Now I want to do the same with the generic type, saving it as a generic type:

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

But this does not compile, so is there a way to achieve the creation of this alias, leaving this type as common?

+62
generics c # alias
Feb 08 '11 at 18:38
source share
2 answers

No no. Type # alias in C # must be a private (otherwise fully resolved) type, so open generics are not supported

This is described in section 9.4.1 of the C # language specification.

Using aliases can call a private configured type, but cannot call an unrelated generic type declaration without providing type arguments.

 namespace N2 { using W = N1.A; // Error, cannot name unbound generic type using X = N1.AB; // 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 } 
+67
Feb 08 '11 at 18:39
source share

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 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 need to replicate those that use the definitions in each file in which you use them, so if you make some changes in the future and forget to update each file, everything will work poorly.

I hope that C # will handle aliases similar to extension methods in the future and allow you to define many of them in a file that you use elsewhere and then maintain them in one place and hide internal unnecessary type mapping data from consumer types .

+4
Jul 04 '12 at 19:12
source share



All Articles