3

有没有更简单的方法来做到这一点?

string s = i["property"] != null ? "none" : i["property"].ToString();

请注意它和 null-coalesce (??) 之间的区别在于,在返回之前访问了非 null 值(?? op 的第一个操作数)。

4

3 回答 3

6

尝试以下

string s = (i["property"] ?? "none").ToString();
于 2011-04-11T19:38:57.143 回答
2

乐趣的替代品。

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; }
}
于 2011-04-11T19:54:44.927 回答
2

如果索引器返回object

(i["property"] ?? (object)"none").ToString()

要不就:

(i["property"] ?? "none").ToString()

如果string

i["property"] ?? "none"
于 2011-04-11T19:39:52.820 回答