Lamba 方法并不完美:它们没有属性并且会导致代码混乱。
如果你想避免这种方法,你可以用另一种方式来做,就像 JavaScript 的.bind()
函数一样。
该函数可以在 C# 中进行如下调整,使用带有一些扩展方法的静态类:
//This code requires the Nu-get plugin ValueTuple
using System.Diagnostics;
public static class Extensions
{
[DebuggerHidden, DebuggerStepperBoundary]
public static WaitCallback Bind(this Delegate @delegate, params object[] arguments)
{
return (@delegate, arguments).BoundVoid;
}
[DebuggerHidden, DebuggerStepperBoundary]
public static Func<object, object> BindWithResult(this Delegate @delegate, params object[] arguments)
{
return (@delegate, arguments).BoundFunc;
}
[DebuggerHidden, DebuggerStepperBoundary]
private static void BoundVoid(this object tuple, object argument)
{
tuple.BoundFunc(argument);
}
[DebuggerHidden, DebuggerStepperBoundary]
private static object BoundFunc(this object tuple, object argument)
{
(Delegate @delegate, object[] arguments) = ((Delegate @delegate, object[] arguments))tuple;
if (argument != null)
if (!argument.GetType().IsArray)
argument = new object[] { argument };
object[] extraArguments = argument as object[];
object[] newArgs = extraArguments == null ? arguments : new object[arguments.Length + extraArguments.Length];
if (extraArguments != null)
{
extraArguments.CopyTo(newArgs, 0);
arguments.CopyTo(newArgs, extraArguments.Length);
}
if (extraArguments == null)
return @delegate.DynamicInvoke(newArgs);
object result = null;
Exception e = null;
int argCount = newArgs.Length;
do
{
try
{
if (argCount < newArgs.Length)
{
object[] args = newArgs;
newArgs = new object[argCount];
Array.Copy(args, newArgs, argCount);
}
result = @delegate.DynamicInvoke(newArgs);
e = null;
} catch (TargetParameterCountException e2)
{
e = e2;
argCount--;
}
} while (e != null);
return result;
}
}
现在您可以为您的方法(不是 lambda)创建一个委托并为其分配一些固定参数:
MessageBox.Show(new Func<double, double, double>(Math.Pow).BindWithResult(3, 2)(null).ToString()); //This shows you a message box with the operation 3 pow 2
因此,下面的代码将产生一个WaitCallback
委托:
new Func<double, double, double>(Math.Pow).Bind(3, 2)
而下面的代码将产生一个Func<object, object>
委托:
new Func<double, double, double>(Math.Pow).BindWithResult(3, 2)