绑定函数(委托)参数 [英] Bind function (delegate) arguments
问题描述
我正在尝试不使用lambda函数来实现以下目标:
I'm trying to achieve the following without using lambda function:
Func<bool> test = () => RunSomething("test"); <-- This work fine but creates lambda
Func<bool> test = bind(RunSomething, "test"); <-- Bind "test" to RunSomething
换句话说,我想知道是否有可能以某种方式绑定Function和arguments.
在C ++中,可以使用std :: bind来实现,但是在C#中可以吗?
In other words I'm want to know if it is possible to somehow bind Function and arguments.
It is possible in C++ using std::bind, but is it possible in C# ?
推荐答案
构建这样的方法很容易,但这将使用lambda表达式实现:
Well it's easy to build such a method, but that would use a lambda expression for the implementation:
public Func<TResult> Bind<T, TResult>(Func<T, TResult> func, T arg)
{
return () => func(arg);
}
同样,对于带有更多参数的函数,有些重载:
And likewise some overloads for functions with more arguments:
public Func<T2, TResult> Bind<T1, T2, TResult>
(Func<T1, T2, TResult> func, T1 arg)
{
return t2 => func(arg, t2);
}
public Func<T2, TResult> Bind<T1, T2, T3, TResult>
(Func<T1, T2, T3, TResult> func, T1 arg)
{
return (t2, t3) => func(arg, t2, t3);
}
继续执行所需的操作-甚至可以添加方法以在调用中绑定多个参数.
Keep going as far as you want - possibly even adding methods to bind more than one argument in a call.
您可以完成所有这些操作而无需使用lambda表达式,但这将需要更多工作.例如:
You can do all this without a lambda expression, but it would just be more work. For example:
public Func<TResult> Bind<T, TResult>(Func<T, TResult> func, T arg)
{
return new Binder<T, TResult>(func, arg).Apply;
}
private sealed class Binder<T, TResult>
{
private readonly T arg;
private readonly Func<T, TResult> func;
internal Binder(Func<T, TResult> func, T arg)
{
this.func = func;
this.arg = arg;
}
public TResult Apply()
{
return func(arg);
}
}
基本上,这就是编译器会使用lambda表达式自动为您执行的操作,那么为什么要自己做呢?
That's basically what the compiler would do for you automatically with a lambda expression, so why do it yourself?
这篇关于绑定函数(委托)参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!