C#泛型:任何方式将泛型参数类型称为集合?
发布时间:2020-12-15 08:04:57 所属栏目:百科 来源:网络整理
导读:我需要编写一堆采用1..N泛型类型参数的方法,例如: int FooT1();int FooT1,T2();int FooT1,T2,T3();...int FooT1,T3...TN(); 在Foo()里面,我想为每种类型做一些事情,例如 int FooT1,T3() { this.data = new byte[3]; // allocate 1 array slot per type} 有
我需要编写一堆采用1..N泛型类型参数的方法,例如:
int Foo<T1>(); int Foo<T1,T2>(); int Foo<T1,T2,T3>(); ... int Foo<T1,T3...TN>(); 在Foo()里面,我想为每种类型做一些事情,例如 int Foo<T1,T3>() { this.data = new byte[3]; // allocate 1 array slot per type } 有没有办法参数化这个,所以我不编辑Foo()的每个变体,类似于: int Foo<T1,T3>() { this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS]; } 理想情况下,我也希望能够获得类型的数组或集合: int Foo<T1,T3>() { this.data = new byte[_NUMBER_OF_GENERIC_PARAMETERS]; // can do this Type [] types = new Type[] { T1,T3 }; // but would rather do this Type [] types = _ARRAY_OR_COLLECTION_OF_THE_GENERIC_PARAMETERS; } 解决方法
您可以从
MethodInfo.GetGenericArguments array中读取当前的通用参数及其编号.
您可以使用 请注意,由于C#和CLI不支持可变参数通用参数列表,因此仍需要使用不同数量的通用参数提供方法的多个泛型重载. 因此,具有三个通用参数的方法的代码示例可以这样写: int Foo<T1,T3>() { MethodInfo mInfo = (MethodInfo)MethodBase.GetCurrentMethod(); Type[] types = mInfo.GetGenericArguments(); this.data = new byte[types.Length]; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |