我需要编写一堆采用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中读取当前的通用参数及其编号.
您可以使用MethodBase.GetCurrentMethod
method检索当前方法的MethodInfo.
请注意,由于C#和CLI不支持可变参数通用参数列表,因此仍需要使用不同数量的通用参数提供方法的多个泛型重载.
因此,具有三个通用参数的方法的代码示例可以这样写:
int Foo<T1,T3>() { MethodInfo mInfo = (MethodInfo)MethodBase.GetCurrentMethod(); Type[] types = mInfo.GetGenericArguments(); this.data = new byte[types.Length]; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。