微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 尝试捕获一个班轮(如“??”或三元运算符)

所以我们有三元运算符.大!那就是??运算符,它对可空变量进行合并.

例:

string emptyIfNull = strValue ?? "";

问题:是否可以为try-catch实现这样的简单运算符?

例:

string result = CoalesceException(someExpression,"");

public static T CoalesceException<T>(expression,defaultValue)
{
    try
    {
        return evaluate expression; // ?
    }
    catch
    {
        return defaultValue;
    }
}

是否有可能实现一种尽可能容易使用的方法,甚至是某种类似于聚结的运算符?

解决方法

您可以:
public static T CoalesceException<T>(Func<T> func,T defaultValue = default(T))
{
    try
    {
        return func();
    }
    catch
    {
        return defaultValue;
    }
}

但我不确定这是你想要的……

使用:

string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString,"");

例如…

string shortString = null;

string emptyIfError = CoalesceException(() => shortString.Substring(10),"");

将返回“”而不是NullReferenceException

重要

写入的函数将始终导致defaultValue的“评估”.含义:

string Throws() { throw new Exception(); }

string str1 = somethingTrue == true ? "Foo" : Throws();

这里不会抛出异常,因为不会计算Throws().同样的事情发生在?操作符.

string str2 = CoalesceException(() => ((string)null).ToString(),Throws());

这将在进入CoalesceException之前导致异常.解:

public static T CoalesceException<T>(Func<T> func,Func<T> defaultValue = null)
{
    try
    {
        return func();
    }
    catch
    {
        return defaultValue != null ? defaultValue() : default(T);
    }
}

使用:

string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString,() => "");

原文地址:https://www.jb51.cc/csharp/243841.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐