【问题标题】:Assign value to Var in C# using try catch在 C# 中使用 try catch 为 Var 赋值
【发布时间】:2013-12-04 21:29:39
【问题描述】:

我想在 C# 中做这样的事情。我认为使用委托或匿名方法可以做到这一点。我试过了,但我做不到。需要帮忙。

SomeType someVariable = try {
                          return getVariableOfSomeType();
                        } catch { Throw new exception(); }

【问题讨论】:

  • 这对我来说很有意义。像往常一样评估表达式,除非表达式的评估导致异常,异常被捕获。 C#try 语句只能包含语句,不能返回值。
  • @hvd:谢谢!从来没想过:-“try 语句只能包含语句,不能返回值”
  • @geedubb :如果您详细解释了为什么代码或问题没有意义,可能会有所帮助。

标签: c# lambda delegates anonymous-methods


【解决方案1】:

你可以创建一个通用的辅助函数:

static T TryCatch<T, E>(Func<T> func, Func<E, T> exception)
  where E : Exception {
  try {
    return func();
  } catch (E ex) {
    return exception(ex);
  }
}

然后你可以这样调用:

static int Main() {
  int zero = 0;
  return TryCatch<int, DivideByZeroException>(() => 1 / zero, ex => 0);
}

这会在TryCatchtry 的上下文中评估1 / zero,从而导致对仅返回0 的异常处理程序进行评估。

我怀疑这会比直接在Main 中的辅助变量和try/catch 语句更具可读性,但如果您遇到这种情况,您可以这样做。

除了ex =&gt; 0,你也可以让异常函数抛出别的东西。

【讨论】:

  • 这更适合 F#。
  • 我对F#不是很熟悉,但是looking at the docs,看来你是对的,F#已经原生支持了。很高兴知道。
  • 模式匹配是件美好的事情。
  • 这正是我想要的。谢谢 HVD!
【解决方案2】:

你应该这样做:

SomeType someVariable;
try {
  someVariable = getVariableOfSomeType();
}
catch {
  throw new Exception();
}

【讨论】:

    【解决方案3】:
    SomeType someVariable = null;
    
    try
    {
        someVariable = GetVariableOfSomeType();
    }
    catch(Exception e)
    {
        // Do something with exception
    
        throw;
    }
    

    【讨论】:

      【解决方案4】:

      你可以试试这个

      try 
      {
          SomeType someVariable = return getVariableOfSomeType();
      } 
      catch { throw; }
      

      【讨论】:

        【解决方案5】:
        SomeType someVariable = null;
        
        try
        {
            //try something, if fails it move to catch exception
        }
        catch(Exception e)
        {
            // Do something with exception
        
            throw;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-15
          • 1970-01-01
          • 2011-12-26
          • 1970-01-01
          • 2018-08-27
          • 2012-11-25
          • 2010-10-31
          相关资源
          最近更新 更多