简体   繁体   English

尝试捕获块宏等效于C#?

[英]A Try-Catch Block Macro equivalent in C#?

Here is a sample C++ macro that I use to make my code more readable and reduce the Try-Catch Clutter: 这是一个示例C ++宏,我使用它来使代码更具可读性并减少Try-Catch杂波:

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

Which can be used as: 可以用作:

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

Please note that I'm looking for STDTRYCATCH that handles any code stub we enclose with it.Is there an equivalent in C# ? 请注意,我在寻找STDTRYCATCH来处理我们附带的任何代码存根.C#中是否有等效代码?

You can write helper: 您可以编写帮助程序:

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;
            }
        }
    }

}

Usage: 用法:

public class MyClass
{
    public void StdException(Exception ex)
    {
        Console.WriteLine("Thrown");
    }

    public void Do()
    {
        this.StdTryCatch(() =>
                         {
                             throw new Exception();
                         });
    }
}

and: 和:

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

But it is not recommeded - due to performance reasons etc - like mentioned in comments. 但由于性能原因等原因,我们不建议这样做,就像评论中提到的那样。

EDIT: Like cdhowie mentioned, you can also prepare inteface: 编辑:cdhowie所述,您还可以准备界面:

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

Then: 然后:

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

}

Your class then need to impelement that interface. 然后,您的班级需要实现该接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM