[英]Generic method with many types
If I want a generic method to have many generic types, eg up to 16. 如果我想要一个泛型方法有许多泛型类型,例如最多16个。
Do I have to overload the method 16 times or is there any smarter way to do this? 我是否必须将方法重载16次,或者有更聪明的方法吗?
public interface IMyInterface { }
public class MyClass {
public void MyMethod<T1>() where T1 : IMyInterface { }
public void MyMethod<T1, T2>() where T1 : IMyInterface where T2 : IMyInterface { }
public void MyMethod<T1, T2, T3>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface { }
public void MyMethod<T1, T2, T3, T4>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface where T4 : IMyInterface { }
// All the way to T16...
// Is there any smarter way of doing this
// instead of having to write it 16 times?
}
if you look at the documentation of Action<T1, T2, ....>
it seems that you need to implement all overloads singlehandedly. 如果你看一下
Action<T1, T2, ....>
的文档,你似乎需要单独实现所有重载。
Here is the reference source of it. 这是它的参考源 。 As you see it is done as in your example.
如您所见,它就像您的示例中那样完成。
A more detailed answer as to why a params
equivalent does not exist can be found by Jon Skeet here . Jon Skeet在这里可以找到更详细的答案,说明为什么不存在
params
等价物。 It states: 它指出:
"Fundamentally Func<T>
and Func<T1, T2>
are entirely unrelated types as far as the CLR is concerned, and there's nothing like params to specify multiple type arguments." “就CLR而言,基本上
Func<T>
和Func<T1, T2>
是完全不相关的类型,并且没有像params那样指定多个类型参数。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.