C#泛型:任何方式将泛型参数类型称为集合?

Cod*_*ien 7 .net c# generics

我需要编写一堆采用1..N泛型类型参数的方法,例如:

int Foo<T1>();
int Foo<T1,T2>();
int Foo<T1,T2,T3>();
...
int Foo<T1,T2,T3...TN>();
Run Code Online (Sandbox Code Playgroud)

在内部,Foo()我想为每种类型做一些事情,例如

int Foo<T1,T2,T3>() {
    this.data = new byte[3]; // allocate 1 array slot per type
}
Run Code Online (Sandbox Code Playgroud)

有没有办法参数化这个,以便我不编辑每个变体Foo(),类似于:

int Foo<T1,T2,T3>() {
    this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS];
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我也希望能够获得一个数组或类型的集合:

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;
}
Run Code Online (Sandbox Code Playgroud)

O. *_*per 8

您可以从MethodInfo.GetGenericArguments数组中读取当前的通用参数及其编号.

您可以MethodInfo使用该MethodBase.GetCurrentMethod方法检索当前方法.

请注意,由于C#和CLI不支持可变参数通用参数列表,因此仍需要使用不同数量的通用参数提供方法的几个泛型重载.

因此,具有三个通用参数的方法的代码示例可以这样写:

int Foo<T1,T2,T3>() {
    MethodInfo mInfo = (MethodInfo)MethodBase.GetCurrentMethod();
    Type[] types = mInfo.GetGenericArguments();

    this.data = new byte[types.Length];
}
Run Code Online (Sandbox Code Playgroud)