byt*_*e77 6 c# exception null-coalescing-operator
所以我们有三元运算符.大!然后是??运算符,它对nullable变量进行合并.
例:
string emptyIfNull = strValue ?? "";
Run Code Online (Sandbox Code Playgroud)
问题:是否可以为try-catch实现这样的简单运算符?
例:
string result = CoalesceException(someExpression, "");
public static T CoalesceException<T>(expression, defaultValue)
{
try
{
return evaluate expression; // ?
}
catch
{
return defaultValue;
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能实现一种尽可能容易使用的方法,甚至是某种类似于聚结的算子?
您可以:
public static T CoalesceException<T>(Func<T> func, T defaultValue = default(T))
{
try
{
return func();
}
catch
{
return defaultValue;
}
}
Run Code Online (Sandbox Code Playgroud)
但我不确定这是你想要的......
使用:
string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, "");
Run Code Online (Sandbox Code Playgroud)
例如...
string shortString = null;
string emptyIfError = CoalesceException(() => shortString.Substring(10), "");
Run Code Online (Sandbox Code Playgroud)
将返回""而不是NullReferenceException
重要
所写的功能将导致defaultValue始终的"评估" .含义:
string Throws() { throw new Exception(); }
string str1 = somethingTrue == true ? "Foo" : Throws();
Run Code Online (Sandbox Code Playgroud)
这里不会抛出异常,因为Throws()不会对其进行评估.同样的情况与??运营商.
string str2 = CoalesceException(() => ((string)null).ToString(), Throws());
Run Code Online (Sandbox Code Playgroud)
这将在进入之前导致异常CoalesceException.解:
public static T CoalesceException<T>(Func<T> func, Func<T> defaultValue = null)
{
try
{
return func();
}
catch
{
return defaultValue != null ? defaultValue() : default(T);
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, () => "");
Run Code Online (Sandbox Code Playgroud)