C# 中等效的 try-catch 块宏

本文关键字:try-catch 块宏 | 更新日期: 2023-09-27 18:36:53

下面是一个示例C++宏,我用它来使我的代码更具可读性并减少 Try-Catch 混乱:

#define STDTRYCATCH(expr)               '
    try {                               '
        return (expr);                  '
    }                                   '
    catch (const std::exception& ex) {  '
        handleException(ex);            '
    }                                   '
    catch (...) {                       '
        handleException();              '
    }

可用作:

int myClass::Xyz()
{
    STDTRYCATCH(myObj.ReadFromDB());
}

请注意,我正在寻找处理我们随附的任何代码存根的 STDTRYCATCH。C# 中有等效项吗?

C# 中等效的 try-catch 块宏

你可以写助手:

public static class ExcetpionHandler
{
    public static void StdTryCatch(this object instance, Action act)
    {
        try
        {
            act();
        }
        catch (Exception ex)
        {
            var method = instance.GetType().GetMethod("StdException");
            if (method != null)
            {
                method.Invoke(instance, new object[] {ex});
            }
            else
            {
                throw;
            }
        }
    }
}

用法:

public class MyClass
{
    public void StdException(Exception ex)
    {
        Console.WriteLine("Thrown");
    }
    public void Do()
    {
        this.StdTryCatch(() =>
                         {
                             throw new Exception();
                         });
    }
}

和:

class Program
{   
    static void Main(string[] args)
    {
        var instance = new MyClass();
        instance.Do();
    }
}

但是由于性能原因等原因,它没有被推荐,如评论中所述。

编辑:就像 cdhowie 提到的,你也可以准备 inteface:

public interface IExceptionHandler 
{
    void StdException(Exception ex);
}

然后:

public static class ExcetpionHandler
{
    public static void StdTryCatch(this IExceptionHandler instance, Action act)
    {
        try
        {
            act();
        }
        catch (Exception ex)
        {
            instance.StdException(ex);
        }
    }
}

然后,您的类需要插入该接口。