是的,這是可能的。 C#3.5增加了對Action
和Func<T>
類型的支持。一個Action不會返回任何值,一個Func總會返回一個值。
你有幾個不同的版本,也接受一些參數。下面的控制檯應用程序介紹瞭如何能做到這一點:
using System;
namespace Stackoverflow
{
class Service
{
public int MyMethod() { return 42; }
public void MyMethod(string param1, bool param2) { }
public int MyMethod(object paramY) { return 42; }
}
class Program
{
static void ExecuteWithRetry(Action action)
{
try
{
action();
}
catch
{
action();
}
}
static T ExecuteWithRetry<T>(Func<T> function)
{
try
{
return function();
}
catch
{
return function();
}
}
static void Main(string[] args)
{
Service s = new Service();
ExecuteWithRetry(() => s.MyMethod("a", true));
int a = ExecuteWithRetry(() => s.MyMethod(1));
int b = ExecuteWithRetry(() => s.MyMethod(true));
}
}
}
正如你所看到的,有兩個重載ExecuteWithRetry
。一個返回的void,一個返回一個類型。您可以撥打ExecuteWithRetry
,通過Action
或Func
。
- >編輯:太棒了!只是一點點額外的代碼來完成這個例子:
使用匿名函數/方法:
ExecuteWithRetry(() =>
{
logger.Debug("test");
});
而且隨着更多的參數(動作,INT)
方法標題:
public static void ExecuteWithRetryX(Action a, int x)
方法調用:
ExecuteWithRetryX(() => { logger.Debug("test"); }, 2);
也許,門面模式可以幫助你。 –