对于项目,我需要将受影响的字符串更改为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;
}
您将从方法返回值,但您没有捕获该返回值。使用返回值更新变量:
string s = "";
s = ValidateString(s); // <--- here
Console.WriteLine(s);
或者,更简单:
Console.WriteLine(ValidateString(""));
您的方法本身也可以简化为:
return string.IsNullOrWhiteSpace(s) ? "défault" : s;
s
没有改变,因为你忽略了ValidateString
方法的返回值,改变你的代码如下:
s= ValidateString(s);
和ValidateString
可以像这样:
static string ValidateString(string s)
{
return string.IsNullOrWhiteSpace(s) ? "défault" : s;
}