模拟C#可变参数模板 [英] Simulate variadic templates in c#
问题描述
有用于模拟在C#中的可变参数模板功能,一个众所周知的方法是什么?
Is there a well known way for simulating the variadic template feature in c#?
例如,我想编写需要一个拉姆达与方法任意设定的参数。这里是伪代码想什么,我有:
For instance, I'd like to write a method that takes a lambda with an arbitrary set of parameters. Here is in pseudo code what I'd like to have:
void MyMethod<T1,T2,...,TReturn>(Fun<T1,T2, ..., TReturn> f)
{
}
感谢您
推荐答案
C#泛型是不一样的C ++模板。 C ++模板被扩展编译时,可以使用可变参数模板参数递归使用。在C ++模板扩张实际上是图灵完备,所以没有从理论上限制什么可以在模板中完成。
C# generics are not the same as C++ templates. C++ templates are expanded compiletime and can be used recursively with variadic template arguments. The C++ template expansion is actually Turing Complete, so there is no theoretically limit to what can be done in templates.
C#泛型是直接编译,用一个空的占位对于将在运行时使用的类型。
C# generics are compiled directly, with an empty "placeholder" for the type that will be used at runtime.
要接受一个lambda采取任何数量的参数,你要么必须产生大量的过载(通过代码生成器)或接受 LambdaExpression
。
To accept a lambda taking any number of arguments you would either have to generate a lot of overloads (through a code generator) or accept a LambdaExpression
.
这篇关于模拟C#可变参数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!