3

在c#中,我可以写这样的东西:

if (
     (
            try {
                ...
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
     ) == true
   )
{
...
}

无需将我所有的 try/catch 块移动到新函数中

- 编辑 -

好的。我完成了我的问题。(也许回答一下)。try/catch 中应该包含的是一种 XmlDocument.TryLoad(stream)(就像有一个 int.tryParse(string))。我只需要一次,所以我想避免做一个额外的功能。所以我的代码会是这样的

            try {
                new XmlDocument().Load(foo);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

我只想知道会不会出错。我不在乎原因(流空,编码错误)。

有很多有趣的答案,但我认为更适合我的是为 xmlDocument 创建扩展方法。这将比在我的声明中强制使用匿名方法更干净(并且可重用且更易于阅读)

4

4 回答 4

10

你不能使用那个确切的语法,不。你可以写:

Func<bool> func = () =>
{
    // Code in here
};

if (func())
{
    ...
}

...但我个人会将其提取到单独的方法中。它可能更具可读性 - 也可能更容易测试。

于 2013-09-03T08:25:41.920 回答
1

并不是说我也建议捕获这样的异常,但是:

    public static bool Try(Action action)
    {
        try
        {
            action();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

示例用法

        int x;
        int a = 0;
        int b = 1;
        if (Try(() => x = a/b))
        {

        }

        if (Try(OtherMethod))
        {

        }

        if (Try(OtherMethod(1,2)))
        {

        }
于 2013-09-03T09:03:16.657 回答
1
if (((Func<bool>)(() =>
{
    // Multi-statement evaluation
    DateTime dt = DateTime.UtcNow;

    if (dt.Hour <= 12)
        return true;
    else
        return false;
}))())
{
    Console.WriteLine("Early");
}
else
{
    Console.WriteLine("Late");
}
于 2016-12-05T16:59:30.173 回答
0

来自C# 语言规范 5.0 (8.7.1):

if 语句根据布尔表达式的值选择要执行的语句。

但是你的代码:

 (
 try { return true; }
 catch (Exception ex) { return false; }
 ) == true

不是一个boolean expression而是一个statement

于 2013-09-03T08:35:51.393 回答