Есть ли более простой способ сделать это в C #?(вопрос типа с нулевым слиянием) - PullRequest
3 голосов
/ 11 апреля 2011

Есть ли более простой способ сделать это?

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

обратите внимание, что разница между ним и null-coalesce (??) заключается в том, что перед возвращением осуществляется доступ к ненулевому значению (первый операнд ?? op).

Ответы [ 3 ]

6 голосов
/ 11 апреля 2011

Попробуйте следующее

string s = (i["property"] ?? "none").ToString();
2 голосов
/ 11 апреля 2011

Альтернатив для веселья.

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; }
}
2 голосов
/ 11 апреля 2011

Если индексатор возвращает object:

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

или просто:

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

Если string:

i["property"] ?? "none"
...