2009-01-11 37 views
36

如何在C#中執行以下操作?寫這段代碼的第一行的正確方法是什麼?如何在C#中爲泛型類創建別名?

using KVP<K, V> = System.Collections.Generic.KeyValuePair<K, V>; 

class C { KVP<int, string> x; } 
+1

正如Eric Lippert所說[這裏](http://stackoverflow.com/q/3720222/303290)「這是一個偶爾需要的功能。」它尚未投入生產。 – mbx 2013-07-04 13:35:00

回答

39

你基本上不能。您只能使用固定的別名,如:

using Foo = System.Collections.Generic.KeyValuePair<int, string>; 

class C { Foo x; } 
+7

drat,這是不幸的 – yoyo 2011-12-17 01:32:00

1

在某些情況下,你可以繼承去:

public class MyList<T1, T2> : List<Tuple<IEnumerable<HashSet<T1>>, IComparable<T2>>> { } 

public void Meth() 
{ 
    var x = new MyList<int, bool>(); 
} 

雖然不是你的具體情況,如KeyValuePair是:-(密封