当字符串为空或为null时,使用.Trim()方法。

33

我从客户端以JSON格式接收到了一些数据。 我正在编写以下代码:

string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
如果从JSON中解析的变量为空,那么当我调用.Trim()方法时,这段代码会崩溃吗?
谢谢。

2
如果它是空的,它会崩溃... - BoltClock
25
(我的值 ?? “”)。Trim() 总是有效的。 - Larry
15
使用C# 6.0,我们现在可以使用空值条件运算符,例如theText?.Trim()。 - Santosh
10个回答

41

3
对于那些不了解Elvis ?:含义的人,请参考https://en.wikipedia.org/wiki/Elvis_operator - Rob Sedgwick
1
这实际上被称为“安全导航运算符”。 Elvis运算符是什么?: https://en.wikipedia.org/wiki/Safe_navigation_operator - cockypup
5
在C#中,它被称为空值条件运算符:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators。 - Marc Selman
1
没人在乎它叫什么,只要它能用就行了 <3 - Dorin Baba

27
如果序列化程序返回空字符串,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();
}

如果你必须修剪大量字段,这会很痛苦,有没有办法扩展修剪方法,以便在字符串为空时不进行修剪? - JsonStatham
1
@SelectDistinct - 你总是可以编写一个扩展方法来实现这一点。 - Oded
@Oded 是的,我有点懒,只是为了参考其他人而发布了这个。 - JsonStatham

17
调用空字符串的 Trim() 方法将返回一个空字符串。调用 nullTrim() 方法将抛出 NullReferenceException 异常。

检查 string.IsNullOrEmptyOrBlank 的最干净的方法是什么? - Paul C
@CodeBlend:你说的"blank"是指什么意思? - Armen Tsirunyan

16

在对字符串进行修剪之前,检查其是否为 null 的一些基本技术:

  • (mystring ?? "").Trim()
    “空合并运算符” ?? 将返回第一个操作数。仅当此操作数为空时,才会返回第二个操作数(作为一种默认值)。
    以上示例将在 mystring 为 null 时返回空字符串
  • mystring?.Trim()
    “空条件运算符” ? 将短路以点符号表示法链接的操作序列。如果操作数为空,则不执行以下操作并返回null。
    以上示例将在 mystring 为 null 时返回null
  • if( string.IsNullOrWhiteSpace(mystring) ) { ... }
    如果您实际上要检查 mystring 中是否有实际内容,则 IsNullOrWhiteSpace() 方法可能会替代修剪。如果操作数为 null、空或只包含空格字符,则该方法返回 true。

15

如果你想要修剪几个字段但是在某些字段中有空值的记录上会出现异常,那么编写一个快速扩展方法将是最简单的方法:

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());

6

根据一些评论的建议,您现在可以使用C# 6中的Null条件运算符并采用以下语法:

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

文档:https://msdn.microsoft.com/zh-cn/library/dn986595.aspx

这个链接是关于IT技术的文件。请点击以上链接查看详细信息。

6
  • No, it would not be better to initialize TheText to "". You're assigning to it right afterwards.

  • No, it won't crash – Trim() works just fine on an empty string. If by "empty" you mean that it can be null, then yes, it will crash; you could have null remain null with a null-conditional call:

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

2
您可以使用org.apache.commons.lang的空值安全运算符trimStringUtils.trim(stringOrNull)来进行操作。"最初的回答"。

问题是关于C#,不是Java。 - Pang

1
最近我需要检查一个字符串是否为null、空或仅包含空格,只使用一个if条件语句。我发现可以将""添加到一个null字符串中,使其变成非null的。这样做可以实现我的需求。
string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception

所以我做了这个替代方案

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

0

你可以使用以下代码

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接