加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:30:42 所属栏目:百科 来源:网络整理
导读:所以我们有三元运算符.大!那就是??运算符,它对可空变量进行合并. 例: string emptyIfNull = strValue ?? ""; 问题:是否可以为try-catch实现这样的简单运算符? 例: string result = CoalesceException(someExpression,"");public static T CoalesceExcep
所以我们有三元运算符.大!那就是??运算符,它对可空变量进行合并.

例:

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,() => "");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读