try ... catch中的隐式类型变量

mel*_*okb 6 .net c# try-catch implicit-typing

我喜欢使用隐式打字几乎所有东西,因为它干净简单.但是,当我需要在单个语句周围包装try ... catch块时,我必须打破隐式类型以确保变量具有已定义的值.这是一个人为的假设例子:

var s = "abc";

// I want to avoid explicit typing here
IQueryable<ABC> result = null;
try {
    result = GetData();
} catch (Exception ex) { }

if (result != null)
    return result.Single().MyProperty;
else
    return 0;
Run Code Online (Sandbox Code Playgroud)

有没有办法可以调用GetData()异常处理,但不必显式定义结果变量的类型?有点像GetData().NullOnException()

usr*_*usr 9

这是一个常见问题.我建议你坚持使用现有的解决方案.

如果你真的想要一个替代品,这里是:

static T NullOnException<T>(Func<T> producer) where T : class {
  try { return producer(); } catch { return null; } //please modify the catch!
}

//now call it
var result = NullOnException(() => GetData());
Run Code Online (Sandbox Code Playgroud)

请修改此项以记录异常或将catch限制为具体类型.我并不认可吞下所有例外情况.

由于这个答案被大量阅读,我想指出这个实现只是演示质量.在生产代码中,您可能应该包含评论中给出的建议.为自己写一个强大的,精心设计的辅助功能,可以为您提供多年的服务.

  • 也许添加第二个`Action <Exception>`来处理异常.我认为catch块在这里只是空的,因为它不影响问题,不是因为那里确实没有. (2认同)