有没有更简单的方法来做到这一点?
string s = i["property"] != null ? "none" : i["property"].ToString();
请注意它和 null-coalesce (??) 之间的区别在于,在返回之前访问了非 null 值(?? op 的第一个操作数)。
有没有更简单的方法来做到这一点?
string s = i["property"] != null ? "none" : i["property"].ToString();
请注意它和 null-coalesce (??) 之间的区别在于,在返回之前访问了非 null 值(?? op 的第一个操作数)。
尝试以下
string s = (i["property"] ?? "none").ToString();
乐趣的替代品。
void Main()
{
string s1 = "foo";
string s2 = null;
Console.WriteLine(s1.Coalesce("none"));
Console.WriteLine(s2.Coalesce("none"));
var coalescer = new Coalescer<string>("none");
Console.WriteLine(coalescer.Coalesce(s1));
Console.WriteLine(coalescer.Coalesce(s2));
}
public class Coalescer<T>
{
T _def;
public Coalescer(T def) { _def = def; }
public T Coalesce(T s) { return s == null ? _def : s; }
}
public static class CoalesceExtension
{
public static string Coalesce(this string s, string def) { return s ?? def; }
}
如果索引器返回object
:
(i["property"] ?? (object)"none").ToString()
要不就:
(i["property"] ?? "none").ToString()
如果string
:
i["property"] ?? "none"