开发者

Is it possible to invoke "n" functions with same return type but with variable parameters using Func or Delegate in C#

Here is my scenario. I have class with 10 methods, those methods are atomic, and are only 10 lines of code max.

So I was thinking, instead of handling the exceptions in each function, would it be possible, to create a delegate (? not sure its the right word here)

That so called wrapped function would execute those atomic function开发者_如何转开发s and handle their exceptions, thus allowing me to centralize exception handling.

Is this possible in C# using delegate or Func, or maybe there is another way to centralize error handling that I might have missed?

Thanks in advance


Yes it is possible here is a code example

using System;

namespace ConsoleApp
{
    class Example {
        public void Run() {
            catchy(crashA); // Calling defined functions
            catchy(crashB);
            catchy(()=> {
                throw new ArgumentException("Anonymous function...");
            });
        }
        void crashA() {
            //...
            throw new ArgumentException("another error");
        }
        void crashB() {
            //...
            throw new ArgumentException("another error");
        }
        void catchy(Action action) {
            try {
                action();
            } catch (Exception ex) {
                Console.WriteLine(ex);
                // do something
            }
        }
    }

    class MainClass
    {

        public static void Main (string[] args)
        {
            new Example().Run();
            Console.ReadLine();
            Console.WriteLine ("Hello World!");
        }
    }
}


yes, with a delegate like this

private delegate MyReturnType MyDelegate(params Object[] a);

but it won't be type safe.


I am not sure if this would work for you, but you could possibly use the "Hole In The Middle" pattern or build an abstract class.

I was trying to do something similar where I wanted certain Pre and Post conditions to occur each time a given method was called. In the same manner you could possibly put your Exception logic there instead of the Pre and Post conditons. Look at this post.

Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜