我正在嘗試創建一個帶參數的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