我需要编写一堆方法,这些方法接受1到N个通用类型参数,例如:
int Foo<T1>();
int Foo<T1,T2>();
int Foo<T1,T2,T3>();
...
int Foo<T1,T2,T3...TN>();
在 Foo()
内,我想针对每种类型做一些操作,例如:
int Foo<T1,T2,T3>() {
this.data = new byte[3]; // allocate 1 array slot per type
}
有没有一种方法可以将这个参数化,以便我不需要编辑每个
Foo()
的变体,类似于以下内容:int Foo<T1,T2,T3>() {
this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS];
}
理想情况下,我还希望能够获取类型的数组或集合:
int Foo<T1,T2,T3>() {
this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS];
// can do this
Type [] types = new Type[] { T1, T2, T3 };
// but would rather do this
Type [] types = _ARRAY_OR_COLLECTION_OF_THE_GENERIC_PARAMETERS;
}
Type
的集合会更合适。(除非你试图捕获可变参数列表的编译时类型,但这也没有太多意义 -params
列表是一个预定类型的数组。) - millimoose