本文介绍了在使用try ... catch隐式类型变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用隐式类型的几乎一切,因为它是干净和简单。然而,当我需要环绕单个语句try ... catch块,我必须打破了隐式类型,以确保变量有一个确定的值。这里有一个人为假设的例子:

I like using implicit typing for almost everything because it's clean and simple. However, when I need to wrap a try...catch block around a single statement, I have to break the implicit typing in order to ensure the variable has a defined value. Here's a contrived hypothetical example:

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;

有没有一种方法,我可以叫的GetData()与异常处理,而无需显式定义结果变量的类型?像的GetData()。NullOnException()

Is there a way I can call GetData() with exception handling, but without having to explicitly define the type of the result variable? Something like GetData().NullOnException()?

推荐答案

这是一个常见的​​问题。我建议你​​只是坚持您现有的解决方案。

This is a common problem. I recommend that you just stick with your existing solution.

如果你真的想要一个选择,那就是:

If you really want an alternative, here it is:

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());

请修改此记录的例外或限制捕捞到一个具体类型。我并不赞同吞下所有的异常。

Please modify this to log the exception or restrict the catch to a concrete type. I do not endorse swallowing all exceptions.

由于这个答案正在读了很多我想指出的是,这个实现仅仅是演示质量。在生产code你应该将在评论中给出的建议。写自己一个强大的,精心设计的辅助功能,将竭诚为您服务好多年了。

As this answer is being read a lot I want to point out that this implementation is just of demo-quality. In production code you probably should incorporate the suggestions given in the comments. Write yourself a robust, well-designed helper function that will serve you well for years.

这篇关于在使用try ... catch隐式类型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:04