使用try-catch为C#中的Var赋值

使用try-catch为C#中的Var赋值,c#,lambda,delegates,anonymous-methods,C#,Lambda,Delegates,Anonymous Methods,我想在C#中做类似的事情。我认为这是可能的使用委托或匿名方法。我试过了,但做不到。我需要帮助 SomeType someVariable = try { return getVariableOfSomeType(); } catch { Throw new exception(); } 你应该这样做: SomeType someVariable; try { someVariable = g

我想在C#中做类似的事情。我认为这是可能的使用委托或匿名方法。我试过了,但做不到。我需要帮助

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

你应该这样做:

SomeType someVariable;
try {
  someVariable = getVariableOfSomeType();
}
catch {
  throw new Exception();
}
你可以试试这个

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

您可以创建通用帮助器函数:

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 T TryCatch(Func-Func,Func异常)
其中E:例外{
试一试{
返回func();
}渔获物(E-ex){
返回异常(ex);
}
}
你可以这样称呼它:

static int Main() {
  int zero = 0;
  return TryCatch<int, DivideByZeroException>(() => 1 / zero, ex => 0);
}
static int Main(){
int零=0;
返回TryCatch(()=>1/0,ex=>0);
}
这将在
TryCatch
try
上下文中计算
1/zero
,导致对异常处理程序进行计算,该处理程序只返回0

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


除了
ex=>0
,您还可以让异常函数抛出其他内容。

这对我来说很有意义。像往常一样对表达式求值,除非表达式求值导致异常,否则会捕获异常。C#
try
语句只能包含语句,不能返回值。@hvd:谢谢!从未想过这一点:-“try语句只能包含语句,不能返回值”@geedubb:如果您详细解释了为什么代码或问题没有意义,可能会有所帮助。这更适合于F#。我对F#不是很熟悉,但似乎您是对的,F#已经在本地支持了这一点。很高兴知道。模式匹配是一件美好的事情。这正是我想要的。谢谢HVD!
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);
}