我目前的代码非常像 python 装饰器,它接受一个函数作为参数并返回由另一个函数包装的相同函数(在本例中打开和关闭 perforce 连接)。
public Func<TArg, TReturn> EnableP4<TReturn, TArgs>(Func<TArg, TReturn> function)
{
Func<TArg, TReturn> p4Wrapper = (TArg funcArg) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) { con.Connect(options); }
return function(funcArg);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
目前这只适用于只有一个参数的函数,我想知道它是否可以变得更通用(也许有一种方法可以将数组解包到方法中?)。
(类似这样的事情?)
public Func<TArgs, TReturn> EnableP4<TReturn, TArgs>(Func<TArgs, TReturn> function)
{
Func<TArgs, TReturn> p4Wrapper = (TArgs args) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) { con.Connect(options); }
return function(*args);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
其中 TArgs 是一个 TArg[]。
最佳答案
你可以只使用 Func<T>
(不是 Func<TArg,TResult>
),并允许编译器通过 lambda 表达式中的闭包为您处理多个参数。
如果您将方法更改为:
public Func<T> EnableP4<T>(Func<T> function)
你总是可以通过以下方式调用它:
var newFunc = EnableP4(() => SomeFunc(arg1, arg2, arg3));
这很好,因为它允许任意数量的参数而无需多次重载。
关于c# - 你能写一个可以接受任意数量参数的 c# 装饰器函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18363338/