【发布时间】:2019-03-05 23:01:43
【问题描述】:
对于一个项目,我需要将受影响的字符串更改为 null 或将空格更改为默认值。 在我看来,这段代码是有道理的,但我错过了什么?它只是返回一个空格,就像它根本没有改变一样。我是编程新手,正在寻求帮助。谢谢你:)。
static void Main(string[] args)
{
string s = "";
ValidateString(s);
Console.WriteLine(s);
}
static string ValidateString(string s)
{
if (s == null || String.IsNullOrWhiteSpace(s))
s = "défault";
return s;
}
【问题讨论】:
-
注意:我发现我可以添加一个“ref”。难道没有更简单的方法吗?
-
@FrankerZ 令人惊讶的是(好的)副本并没有显示如何实际处理字符串(所以不是锤击)......也许stackoverflow.com/questions/1948978/… 会做得更好?
-
仅供参考,如果字符串为
null,IsNullOrWhiteSpace将返回true,因此除此之外您不需要s == null。