C# 4.0 模式/架构/匿名方法
我对C#比较陌生,也许你能帮我解决这个问题 我得到了两个调用特定服务的方法C# 4.0 模式/架构/匿名方法,c#-4.0,design-patterns,C# 4.0,Design Patterns,我对C#比较陌生,也许你能帮我解决这个问题 我得到了两个调用特定服务的方法callservicerxy(param1,param2,…)。由于许多原因,这些服务电话可能会出错(我并不真正关心最终的原因)。所以基本上我需要用这样的东西来包装它们——如果出现问题,让它们再次执行: var i = 3; while(i>0) try{ call...() } catch{ i--; } i=0; } 我宁愿只写一次代码。我能有一个像tryXtimes(intx,ca
callservicerxy(param1,param2,…)
。由于许多原因,这些服务电话可能会出错(我并不真正关心最终的原因)。所以基本上我需要用这样的东西来包装它们——如果出现问题,让它们再次执行:
var i = 3;
while(i>0)
try{
call...()
} catch{
i--;
}
i=0;
}
我宁愿只写一次代码。我能有一个像tryXtimes(intx,callService())
这样的方法来执行一个未定义或匿名的方法吗?(我脑子里有Javascript,这在哪里是可能的…?是的,这是可能的。C#3.5增加了对Action
和Func
类型的支持。操作不会返回任何值,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));
}
}
}
并具有更多参数(action,int)
方法标题:
public static void ExecuteWithRetryX(Action a, int x)
方法调用:
ExecuteWithRetryX(() => { logger.Debug("test"); }, 2);
对此,我将使用策略/工厂模式。这个答案给出了使用带有链接的策略/工厂模式的示例。上面链接中的问题将为您提供另一种可以采用此模式的示例 这些设计模式有很多很好的例子,下面是和的详细介绍。最后两个链接中的前一个链接还向您展示了如何将这两个链接结合起来,以实现您所需的功能 我希望这有帮助 试试下面的内容
void CallServiceXY(params object []objects)
{
Console.WriteLine("a");
throw new Exception("");
}
void Retry(int maxRetryCount, Action<object[]> action, params object[] obj)
{
int retryCount = 1;
while ( retryCount <= maxRetryCount)
{
try
{
action(obj);
return;
}
catch
{
retryCount++;
}
}
}
void Main()
{
Retry(2,CallServiceXY);
Retry(2,CallServiceXY,"");
Retry(2,CallServiceXY,"","");
}
void callservicerxy(参数对象[]对象)
{
控制台。写入线(“a”);
抛出新异常(“”);
}
无效重试(int-maxRetryCount,Action-Action,params-object[]obj)
{
int-retryCount=1;
虽然(可能是retryCount),Facade模式可以帮助您。Action和Func自.NET2.0以来就存在。
void CallServiceXY(params object []objects)
{
Console.WriteLine("a");
throw new Exception("");
}
void Retry(int maxRetryCount, Action<object[]> action, params object[] obj)
{
int retryCount = 1;
while ( retryCount <= maxRetryCount)
{
try
{
action(obj);
return;
}
catch
{
retryCount++;
}
}
}
void Main()
{
Retry(2,CallServiceXY);
Retry(2,CallServiceXY,"");
Retry(2,CallServiceXY,"","");
}