我正在尝试创建一个带参数的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");
}
https://msdn.microsoft.com/en-us/library/w5zay9db.aspx –
如果我理解正确,你想要的东西类似于C++ variadic模板。看看这个答案:http://stackoverflow.com/questions/6844890/simulate-variadic-templates-in-c-sharp –
@李泰勒。我不认为params会起作用......但如果你能以其他方式展示我会很高兴。 – Raymond