3

これを行う簡単な方法はありますか?

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

これとnull合体(??)の違いは、null以外の値(?? opの最初のオペランド)が戻る前にアクセスされることです。

4

3 に答える 3

6

次を試してください

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

インデクサーが返す場合object

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

あるいは単に:

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

場合string

i["property"] ?? "none"
于 2011-04-11T19:39:52.820 に答える
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 に答える