我从客户端以JSON格式接收到了一些数据。 我正在编写以下代码:
string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
如果从JSON中解析的变量为空,那么当我调用.Trim()方法时,这段代码会崩溃吗?谢谢。
我从客户端以JSON格式接收到了一些数据。 我正在编写以下代码:
string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());
如果从JSON中解析的变量为空,那么当我调用.Trim()方法时,这段代码会崩溃吗?GetNullableString()?.Trim(); // returns NULL or trimmed string
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
异常。string.IsNullOrEmptyOrBlank
的最干净的方法是什么? - Paul C在对字符串进行修剪之前,检查其是否为 null
的一些基本技术:
(mystring ?? "").Trim()
??
将返回第一个操作数。仅当此操作数为空时,才会返回第二个操作数(作为一种默认值)。mystring?.Trim()
?
将短路以点符号表示法链接的操作序列。如果操作数为空,则不执行以下操作并返回null。if( string.IsNullOrWhiteSpace(mystring) ) { ... }
IsNullOrWhiteSpace()
方法可能会替代修剪。如果操作数为 null、空或只包含空格字符,则该方法返回 true。如果你想要修剪几个字段但是在某些字段中有空值的记录上会出现异常,那么编写一个快速扩展方法将是最简单的方法:
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());
根据一些评论的建议,您现在可以使用C# 6中的Null条件运算符并采用以下语法:
string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();
这个链接是关于IT技术的文件。请点击以上链接查看详细信息。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();
org.apache.commons.lang
的空值安全运算符trim
StringUtils.trim(stringOrNull)
来进行操作。"最初的回答"。string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception
所以我做了这个替代方案
string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true
你可以使用以下代码
string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();