如何将空字符串更改为默认值

问题描述 投票:0回答:2

对于项目,我需要将受影响的字符串更改为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;
    }
c# string null
2个回答
5
投票

您将从方法返回值,但您没有捕获该返回值。使用返回值更新变量:

string s = "";
s = ValidateString(s); // <--- here
Console.WriteLine(s);

或者,更简单:

Console.WriteLine(ValidateString(""));

您的方法本身也可以简化为:

return string.IsNullOrWhiteSpace(s) ? "défault" : s;

-1
投票

s没有改变,因为你忽略了ValidateString方法的返回值,改变你的代码如下:

s= ValidateString(s);    

ValidateString可以像这样:

static string ValidateString(string s)
{
    return string.IsNullOrWhiteSpace(s) ? "défault" : s;
}
© www.soinside.com 2019 - 2024. All rights reserved.