覆盖空条件运算符的默认值

时间:2019-10-18 08:14:05

标签: c# .net

以下是非常简单的代码

   public static void Main()
    {
        string mode = null;
        string abc = mode?.ToLower();
        if(abc == "cs")
        {
            Console.WriteLine("not null");
        }
        Console.WriteLine(abc);
    }

我在变量 abc 中得到一个空字符串。我想为?。运算符自定义返回值。我该怎么办?

2 个答案:

答案 0 :(得分:7)

对于null,您可以将null conditionalnull-coalescing operator一起使用,这将为您提供默认值;

string abc = mode?.ToLower() ?? "somethingelse";

或者您可以编写自己的扩展方法,加入胡椒粉和盐调味

public static string DefaultIfEmpty(this string str, string defaultValue, bool considerWhiteSpaceIsEmpty = false)
   => (considerWhiteSpaceIsEmpty ? string.IsNullOrWhiteSpace(str) : string.IsNullOrEmpty(str)) ? defaultValue : str;

答案 1 :(得分:1)

您不能修改?-如果您的字符串为null,则不会评估ToLower()。

您可以将null换行:

using System;

public class Program
{
    public static void Main()
    {
        string mode = null;
        string abc = (mode ?? "BIG").ToLower(); 
        if (abc == "cs")  // abc is "big" here
        {
            Console.WriteLine("not null");
        }

        Console.WriteLine(abc);
    }
}