gpt4 book ai didi

c# - 绑定(bind)函数(委托(delegate))参数

转载 作者:太空狗 更新时间:2023-10-30 01:18:29 26 4
gpt4 key购买 nike

我试图在不使用 lambda 函数的情况下实现以下目标:

Func<bool> test = () => RunSomething("test");  <-- This work fine but creates lambda
Func<bool> test = bind(RunSomething, "test"); <-- Bind "test" to RunSomething

换句话说,我想知道是否有可能以某种方式绑定(bind)函数和参数。
在 C++ 中使用 std::bind 是可能的,但在 C# 中是否可能?

最佳答案

好吧,构建这样的方法很容易,但是会使用 lambda 表达式来实现:

public Func<TResult> Bind<T, TResult>(Func<T, TResult> func, T arg)
{
return () => func(arg);
}

同样还有一些带有更多参数的函数的重载:

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);
}

想走多远就走多远——甚至可能添加方法以在一次调用中绑定(bind)多个参数。

可以在没有 lambda 表达式的情况下完成所有这些,但这只会增加工作量。例如:

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 表达式自动为您做的事情,那么为什么要自己做呢?

关于c# - 绑定(bind)函数(委托(delegate))参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27250963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com