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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...