簡體   English   中英

在C#中有更簡單的方法嗎? (null-coalescing type question)

[英]Is there an easier way to do this in C#? (null-coalescing type question)

有更簡單的方法嗎?

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

注意它和null-coalesce(??)之間的區別是在返回之前訪問not-null值(op的第一個操作數)。

請嘗試以下方法

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

如果indexer返回object

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

要不就:

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

如果string

i["property"] ?? "none"

有趣的替代品。

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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM