C# 如何使方法自动包含在try-catch块中

C# 如何使方法自动包含在try-catch块中,c#,try-catch,C#,Try Catch,比如说,我们有类似于: public CustomType DoSomething1() { CustomType ct = new CustomType(); try { // do something } catch(Exception e) { ct.Passed = false; } return ct; } public CustomType DoSomething2() { CustomType ct = new C

比如说,我们有类似于:

public CustomType DoSomething1() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}

public CustomType DoSomething2() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}

public CustomType DoSomething3() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}
这些方法由另一个程序使用反射执行,如果CustomType属性Passed==false,则程序停止执行另一个程序。这是由于架构方面的原因

是否可以创建一些属性或类似的东西来避免使用try-catch,这样,若在方法中抛出异常,它将使传递的属性为false并返回到程序?例如

[CatchException('Passed', false)]
public CustomType DoSomething1() {
   CustomType ct = new CustomType();
   // do something
   return ct;
}

如果在“做某事”的过程中会抛出错误,则ct.Passed将等于“false”

如果我正确理解您的问题,您希望避免重复try-catch块。您可以通过创建一个传递您想要处理的逻辑的函数来解决这个问题

public static CustomType CatchException(Action a)
{
    CustomType ct = new CustomType();
    try
    {
        a();
    }
    catch
    {
        ct.Passed = false;
    }
    return ct;
}
现在,您可以轻松地使用所需的任何逻辑多次调用该函数

public CustomType DoSomething1()
{
    return CatchException(() =>
    {
        //Do something
    });
}
...

您可以执行以下操作:

public static T SafeProcessing<T>(Action<T> action, Action<T> onFail)
    where T: new()
{
     var t = new T();

     try
     {
         a(t);
     }
     catch (Exception e)
     {
          //Log e
          onFail(t);
     }

     return t;
 }

c#不支持开箱即用。能否将try catch移到调用方逻辑?或者这是开箱即用的?C不支持开箱即用的装饰程序。您可以创建一个属性,但在最后,您需要检查属性的存在性并执行您自己的逻辑。返回类型如何,这种方法是否仅适用于
void
方法?在我第一次拍摄时,返回类型缺失。我已经添加了@r1verside
return SafeProcessing(c => DoSomething(c), c => c.Safe = false);