【发布时间】:2010-05-02 00:20:05
【问题描述】:
我有一个示例程序,它需要按特定顺序执行 3 个方法。 并且在执行每个方法之后,都应该做错误处理。现在我以正常方式执行此操作,不使用这样的委托。
类程序 { 公共静态无效 Main() {
MyTest();
}
private static bool MyTest()
{
bool result = true;
int m = 2;
int temp = 0;
try
{
temp = Function1(m);
}
catch (Exception e)
{
Console.WriteLine("Caught exception for function1" + e.Message);
result = false;
}
try
{
Function2(temp);
}
catch (Exception e)
{
Console.WriteLine("Caught exception for function2" + e.Message);
result = false;
}
try
{
Function3(temp);
}
catch (Exception e)
{
Console.WriteLine("Caught exception for function3" + e.Message);
result = false;
}
return result;
}
public static int Function1(int x)
{
Console.WriteLine("Sum is calculated");
return x + x;
}
public static int Function2(int x)
{
Console.WriteLine("Difference is calculated ");
return (x - x);
}
public static int Function3(int x)
{
return x * x;
}
}
如您所见,这段代码看起来很难看,有这么多的 try catch 循环,它们都在做同样的事情......所以我决定我可以使用委托来重构这段代码,以便可以全部推动 Try Catch成一种方法,使它看起来整洁。我在网上查看了一些示例,但无法确定我是否应该为此使用 Action 或 Func 代表。两者看起来相似,但我无法清楚地知道如何实现这一点。非常感谢任何帮助。我使用的是 .NET 4.0,所以我也允许为此使用匿名方法 n lambda 表达式
谢谢
【问题讨论】:
标签: .net-3.5 delegates action func