检查字符串是否为空或空,否则修剪它

10 c# string null

我尝试了以下方法:

dummy.Title = ds1Question.Title.null ? "Dummy title" : ds1Question.Title.Trim();
Run Code Online (Sandbox Code Playgroud)

我期待看到像nulloremptyintellisense这样的东西,但似乎没有什么可以做到这一点.还有其他方法可以做到这一点吗?

Jon*_*eet 25

这是无效的:

 ds1Question.Title.null
Run Code Online (Sandbox Code Playgroud)

你可以有:

dummy.Title = ds1Question.Title == null ? "Dummy title"
                                        : ds1Question.Title.Trim();
Run Code Online (Sandbox Code Playgroud)

或使用:

dummy.Title = (ds1Question.Title ?? "Dummy title").Trim();
Run Code Online (Sandbox Code Playgroud)

这将执行不必要的修剪到默认值,但它很简单.

这些只会检查无效.要检查是否为空,您需要调用String.IsNullOrEmpty,我通过额外的变量进行调用以获得理智:

string title = ds1Question.Title;
dummy.Title = string.IsNullOrEmpty(title) ? "Dummy title" : title.Trim();
Run Code Online (Sandbox Code Playgroud)

或者IsNullOrWhitespace根据Marc的回答使用,以避免标题为"",在修剪之前不是空.


The*_*aot 12

您可以更进一步了解Justin Harvey 建议并实现扩展方法(当然是在静态类中),如下所示:

public static string TrimmedOrDefault(this string str, string def)
{
    if (string.IsNullOrEmpty(str)) //or if (string.IsNullOrWhiteSpace(str))
    {
        // Hmm... what if def is null or empty?
        // Well, I guess that's what the caller wants.
        return def; 
    }
    else
    {
        return str.Trim();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

dummy.Title = ds1Question.Title.TrimmedOrDefault("Dummy title");
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 11

也许:

dummy.Title = string.IsNullOrEmpty(ds1Question.Title)
             ? "Dummy title" : ds1Question.Title.Trim();
Run Code Online (Sandbox Code Playgroud)

要么

dummy.Title = string.IsNullOrWhiteSpace(ds1Question.Title)
             ? "Dummy title" : ds1Question.Title.Trim();
Run Code Online (Sandbox Code Playgroud)