【问题标题】:How to change a null string to default如何将空字符串更改为默认值
【发布时间】: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”。难道没有更简单的方法吗?
  • C# string reference type?的可能重复
  • @FrankerZ 令人惊讶的是(好的)副本并没有显示如何实际处理字符串(所以不是锤击)......也许stackoverflow.com/questions/1948978/… 会做得更好?
  • 仅供参考,如果字符串为 nullIsNullOrWhiteSpace 将返回 true,因此除此之外您不需要 s == null

标签: c# string null


【解决方案1】:

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

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

或者,更简单地说:

Console.WriteLine(ValidateString(""));

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

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

【讨论】:

    【解决方案2】:

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

    s= ValidateString(s);    
    

    ValidateString 可以这样改进:

    static string ValidateString(string s)
    {
        return string.IsNullOrWhiteSpace(s) ? "défault" : s;
    }
    

    【讨论】:

    • 方法优化不错,但没有解决问题。
    • 如果您添加了关于 OP 做错了什么以及如何解决问题的解释将会很有帮助(如果没有一些描述,纯代码的答案通常没有帮助)
    猜你喜欢
    • 2013-04-15
    • 2012-08-13
    • 2011-04-09
    • 1970-01-01
    • 2011-04-28
    • 2020-07-07
    • 2022-12-04
    • 1970-01-01
    • 2012-01-30
    相关资源
    最近更新 更多