.当字符串为空或空时,Trim()

本文关键字:Trim 字符串 | 更新日期: 2023-09-27 18:18:25

我以json的形式从客户端接收一些数据。我正在写这个:

string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());

如果从 json 解析的变量返回空,则当我调用 .Trim(( 方法?

谢谢。

.当字符串为空或空时,Trim()

您可以使用 elvis 运算符,也称为"null 条件运算符":

GetNullableString()?.Trim(); // returns NULL or trimmed string

更多信息: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators

如果序列化程序返回空字符串,Trim将不执行任何操作。

如果序列化程序返回 null ,您将在调用 Trim 时得到一个NullReferenceException

您的代码最好编写(就初始化而言(,如下所示:

string theText = 
            ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());

声明和初始化变量并立即分配给它是没有意义的。

如果您不知道序列化程序可能返回的内容,则以下内容是最安全的:

string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));
if(!string.IsNullOrEmpty(theText))
{
    theText = theText.Trim();
}

对空字符串调用Trim()将导致空字符串。在null上呼叫Trim()会抛出NullReferenceException

如果您希望修剪一些字段,但在某些字段中具有空值的记录出现异常,那么编写快速扩展方法将是最简单的方法:

public static class ExtensionMethods
    {
        public static string TrimIfNotNull(this string value)
        {
            if (value != null)
            {
                return value.Trim();
            }
            return null;
        }
    }

使用示例:

string concatenated = String.Format("{0} {1} {2}", myObject.fieldOne.TrimIfNotNull(), myObject.fieldTwo.TrimIfNotNull(), myObject.fieldThree.TrimIfNotNull());

在修剪之前检查字符串null的一些基本技术:


  • (mystring ?? "").Trim()"空合并运算符"??将返回第一个操作数。仅当此操作数为 null 时,才会返回第二个操作数(作为一种默认值(。
    如果 mystring 为空,上面的示例将返回一个空字符串

  • mystring?.Trim()"null 条件运算符"?将以点表示法缩短操作链。如果操作数为 null,则不会执行以下操作,并且将返回 null。
    如果 mystring 为 null,则上面的示例将返回 null

  • if( string.IsNullOrWhiteSpace(mystring) ) { ... }如果您真的想检查 MyString 中是否有真实内容,IsNullOrWhiteSpace() 方法可能会取代修剪。如果操作数为 null、空或只为空格字符,则返回 true。

如某些注释中所建议的,您现在可以使用以下语法使用 c# 6 Null 条件运算符:

string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();

文档:https://msdn.microsoft.com/en-us/library/dn986595.aspx

  • 不,将TheText初始化为""不会更好。之后,您将立即分配给它。

  • 不,它不会崩溃——Trim()空字符串上工作得很好。如果您所说的"空"是指它可以为空,那么是的,它会崩溃;您可以使用空条件调用使 null 保持 null

    string TheText =
        serializer.ConvertToType<string>(dictionary["TheText"])?.Trim();
    

你可以用这段代码作为 beblow

 string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();

最近我不得不只使用一个 if 条件检查一个字符串是空、空还是空格,为此我发现您可以将 " 添加到空字符串以使其非空。

string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception

所以我改做了这个

string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true