【发布时间】:2016-02-02 20:59:45
【问题描述】:
我正在尝试创建一个带有参数的 func 的扩展方法。我想支持可变数量的参数(无、1、2、...10)
我有这样的东西,恰好适用于三个参数。 如何简化它以支持可变数量的参数,而不必为每个排列复制和粘贴?有可能吗?
(注意:我的示例非常简单。我的实际实现有更多逻辑,例如支持具有计数、Thread.Sleep、跟踪日志记录、异常处理等的“重试”逻辑)
谢谢!
public static class UtilExtensions
{
public static TResult Execute<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> function, T1 argument1, T2 argument2, T3 argument3))
{
// do other stuff ... like logging
try
{
// call our 'action'
TResult result = function(argument1, argument2, argument3);
return result;
}
catch (Exception ex)
{
// do other stuff ... like logging, handle Retry logic, etc.
}
}
}
它是这样调用的:
public string DoSomething(int arg1, string arg2, MyObject arg3)
{
if (arg1 == 1)
throw new Exception("I threw an exception");
return "I ran successfully";
}
public string DoSomethingElse()
{
return "blah blah blah";
}
public string DoSomethingMore(DateTime dt)
{
return "hi mom";
}
[TestMethod]
public void Should_call_UtilsExtensions_Execute_method_successfully()
{
int p1 = 0;
string p2 = "Hello";
MyObject p3 = new MyObject();
string results = UtilExtensions.Execute<int, string, MyObject, string>(
DoSomething, p1, p2, p3);
// ??? So how would I use my UtilExtensions api to call
// DoSomethingElse (no arguments)
// DoSomethingMore (one argument)
// I'm okay to create overloads of my Execute method
// but I don't want to copy-and-paste the same code/logic in each method
results.Should().Be("I ran successfully");
}
【问题讨论】:
-
如果我理解正确你想要的是类似于 C++ 可变参数模板的东西。看看这个答案:stackoverflow.com/questions/6844890/…
-
@李·泰勒。我不认为 params 会起作用......但如果你能告诉我其他方式,我会很高兴。
-
我相信如果你放弃强类型化并在 System.Delegate 上创建扩展方法,params 会起作用
-
@Raymond - 请解释为什么你认为
params行不通
标签: c# lambda anonymous-function func