2011-12-18 48 views
11

我以json的形式从客户端接收一些数据。 我写这篇文章:.Trim()当字符串为空或为空时

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

如果一个本是从JSON解析的变量回到空,这段代码崩溃时,我调用.Trim()方法?

谢谢。

+2

好吧,如果它为空,它会崩溃。 .. – BoltClock 2011-12-18 20:48:33

+19

(myValue ?? “”).Trim()将全部工作。 – Larry 2012-11-30 13:33:22

+8

在C#6.0中,我们现在可以使用空条件运算符,比如Text?.Trim() – Santosh 2016-08-06 11:32:48

回答

17

如果串行返回一个空字符串,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(); 
} 
+1

好的,这使得更清晰。 – frenchie 2011-12-19 04:17:37

+0

如果你必须修剪大量的字段,这是一个痛苦,如果字符串为空,是否没有办法扩展trim方法以避免打扰? – JsonStatham 2015-06-25 14:26:33

+1

@SelectDistinct - 你总是可以写一个扩展方法来做到这一点。 – Oded 2015-06-25 14:27:08

2

首先,不,不是更好地初始化TheText""。之后你就会分配给它。 (如果你曾经确实需要使用一个空字符串,使用string.Empty代替它通常是清晰,只是通常更好的做法。)

其次,不,它不会崩溃 - Trim()作品就好了一个空字符串。如果通过“空”你的意思是它可以是null,那么是的,它会崩溃;你可以修复,通过使用空聚结操作:

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

我不认为'string.Empty'比''“'更好。我更喜欢''“'。 – CodesInChaos 2011-12-18 20:52:28

+0

@CodeInChaos:不,没有普遍的一致意见。这主要是意见,但可能有一些优点[效率参数](http://stackoverflow.com/questions/5650164/why-string-empty-is-more-recommended-than)。但这只是一个建议。 – Ryan 2011-12-18 20:55:20

+2

我敢肯定,效率参数没有任何优点.net 4.我的测试显示''''和'string.Empty'指向同一个实例,并且该实例在AppDomains之间共享。使用NGen可能会有所不同,但至少在正常程序中,我无法找到这两者之间的技术差异。 – CodesInChaos 2011-12-18 21:21:11

10

上一个空字符串调用Trim()将导致一个空字符串。呼吁nullTrim()将抛出NullReferenceException

+0

什么是最简洁的方式来检查'string.IsNullOrEmptyOrBlank'? – Coops 2013-02-01 15:11:48

+0

@CodeBlend:你是什么意思的空白? – 2013-02-01 18:14:15

+2

Aha - [String.IsNullOrWhiteSpace](http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx) – Coops 2013-02-04 09:05:21

9

如果你想修剪几个字段,但是对于那些在某些领域空,然后写一个快速的扩展方法将是最简单的方法记录你获得例外:

使用
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()); 
5

您可以使用Elvis操作符:

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

https://en.wikipedia.org/wiki/Elvis_operator对于那些不知情者猫王的意义是什么? – 2017-01-23 16:07:34

0

您可以使用此代码作为beblow

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