试一试(如“??”或三元运算符)

时间:2015-03-20 07:52:08

标签: c# exception null-coalescing-operator

所以我们有三元运算符。大!然后是??运算符,它在nullable变量上进行合并。

示例:

string emptyIfNull = strValue ?? "";

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

示例:

string result = CoalesceException(someExpression, "");

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

是否有可能实现一种尽可能容易使用的方法,甚至是某种类似合并的算子呢?

2 个答案:

答案 0 :(得分:8)

你可以:

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

答案 1 :(得分:1)

这里有一些我最终要创建One Liner TryCatch的东西

<强>用法

SELECT UserName, Email, Dashboard_Name, RID, Dashboard.ID as Dashboard_ID, KPI_Name, KPI.ID as KPI_ID,Chart.ID as Chart_ID, Chart_Name
  from [User]
  inner join [Dashboard]  on [Dashboard].[USER_ID]=[User].Email
              and [User].Email=@p_email 
  Inner Join [KPI] ON [Dashboard].[Dashboard_ID] = [KPI].[Dashboard_ID]
  Inner Join [Chart] ON [KPI].[ID] = [Chart].[KPI_ID]

TryCatch定义

  var r = Task.TryCatch(() => _logic.Method01(param1, param2));