我如何使用 Action重构此代码?或 Func代表们

发布于 2024-08-31 16:28:50 字数 1542 浏览 2 评论 0原文

我有一个示例程序,它需要按特定顺序执行 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 表达式,

谢谢

I have a sample program, which needs to execute 3 methods in a particular order.
And after executing each method, should do error handling. Now i did this in a normal fashion, w/o using delegates like this.

class Program
{
public static void 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;
    }
}

As you can see, this code looks ugly w/ so many try catch loops, which are all doing the same thing...so i decided that i can use delegates to refactor this code so that Try Catch can be all shoved into one method so that it looks neat. I was looking at some examples online and couldnt figure our if i shud use Action or Func delegates for this. Both look similar but im unable to get a clear idea how to implement this. Any help is gr8ly appreciated. I'm using .NET 4.0, so im allowed to use anonymous methods n lambda expressions also for this

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执笔绘流年 2024-09-07 16:28:50
bool result = true;
int m = 2;
int temp = 0;

var funcs = new Func<int, int>[]{
                          x =>
                              {
                                  Console.WriteLine("Sum is calculated");
                                  return x + x;
                              },
                          x =>
                              {
                                  Console.WriteLine("Difference is calculated");
                                  return x - x;
                              },
                          x => x * x
                      };

temp = m;
foreach (var func in funcs)
{
    try
    {
        temp = func(m);
    }
    catch (Exception e)
    {
        Console.WriteLine("Caught exception:" + e.Message);
        result = false;
    }                
 }

就像另一个答案所说的那样,对于这个简单的例子来说这可能有点矫枉过正。但是,在某些情况下它仍然很有用,例如,如果您想在每个步骤中实现一些重试逻辑(假设您正在做比计算值更复杂的事情)

bool result = true;
int m = 2;
int temp = 0;

var funcs = new Func<int, int>[]{
                          x =>
                              {
                                  Console.WriteLine("Sum is calculated");
                                  return x + x;
                              },
                          x =>
                              {
                                  Console.WriteLine("Difference is calculated");
                                  return x - x;
                              },
                          x => x * x
                      };

temp = m;
foreach (var func in funcs)
{
    try
    {
        temp = func(m);
    }
    catch (Exception e)
    {
        Console.WriteLine("Caught exception:" + e.Message);
        result = false;
    }                
 }

Like another answer says, this can be overkill for this simple example. However it could still be useful in some cases, for example if you want to implement some retrying logic at each step (assuming you're doing something more complex than calculating values)

饮惑 2024-09-07 16:28:50

感谢您的回复...我能够想出这个解决方案

@joel...thnx for the soln...正如你所看到的,抛出的异常无法终止程序...它在记录后会继续例外..
这是我的代码
不知怎的,我仍然觉得这可以/应该进一步重构。!!我只是不知道如何:(

任何进一步简化这个的建议..

注意:如果一个特定的函数抛出异常,那么总体结果应该是错误的...但是应该继续执行其他函数以查看是否有任何其他函数失败...

另外,这里提到的func只是为了说明,实际方法更多cmplx

class Program
{
    public static void Main()
    {
        ExecuteTask task1 = Function1;
        ExecuteTask task2 = Function2;
        ExecuteTask task3 = Function3;
        bool result = true;
        int param1 = 2, param2 = 3, param3 = 4;

        MyTest(task1, ref result, ref param1);
        MyTest(task2, ref result, ref param2);
        MyTest(task3, ref result, ref param3);

        Console.WriteLine("final result is " + result.ToString());
        Console.ReadLine();
    }

    private delegate void ExecuteTask(ref int x);

    private static void MyTest(ExecuteTask task, ref bool result1, ref int param1)
    {

        try
        {
            task(ref param1);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for " + e.Message);
            result1 = false;
        }

        return result1;
    }

    public static void Function1(ref int x)
    {
        Console.WriteLine("Sum is calculated");
        x = x + x;
    }

    public static void Function2(ref int x)
    {
        Console.WriteLine("Difference is calculated ");
        x = (2 * x - x);
    }

    public static void Function3(ref int x)
    {
        //Console.WriteLine("Product is calculated ");
        //x = x * x;
        throw new ArgumentOutOfRangeException();
    }
}

Thanks for the response...I was able to come up with this solution

@joel....thnx for the soln...as you can see, the excpetion thrown cant terminate the program....it shud continue after logging the exception..
here is my code
I somehow still, feel that this can/shud be further refactored.!! i just donno how :(

any suggestions for further simplifying this..

Note: If a particular function throw an exception, the overall result shud be false...but shud continue executing other func's to see if any other func fails...

Also, the func's mentioned here are just for illustration, actual methods are more cmplx

class Program
{
    public static void Main()
    {
        ExecuteTask task1 = Function1;
        ExecuteTask task2 = Function2;
        ExecuteTask task3 = Function3;
        bool result = true;
        int param1 = 2, param2 = 3, param3 = 4;

        MyTest(task1, ref result, ref param1);
        MyTest(task2, ref result, ref param2);
        MyTest(task3, ref result, ref param3);

        Console.WriteLine("final result is " + result.ToString());
        Console.ReadLine();
    }

    private delegate void ExecuteTask(ref int x);

    private static void MyTest(ExecuteTask task, ref bool result1, ref int param1)
    {

        try
        {
            task(ref param1);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for " + e.Message);
            result1 = false;
        }

        return result1;
    }

    public static void Function1(ref int x)
    {
        Console.WriteLine("Sum is calculated");
        x = x + x;
    }

    public static void Function2(ref int x)
    {
        Console.WriteLine("Difference is calculated ");
        x = (2 * x - x);
    }

    public static void Function3(ref int x)
    {
        //Console.WriteLine("Product is calculated ");
        //x = x * x;
        throw new ArgumentOutOfRangeException();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文