柚子Nan--回归原点

Everything can be as easy as you like or as complex as you need.
posts - 232, comments - 984, trackbacks - 17, articles - 29
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

1  关于字符串的比较

在印象中,字符串比较的方式很多,至少有下列四种写法

string strA = "koffer", strB = "KoffER" ;

                if(strA.ToUpper() == strB.ToUpper())

                {

                }

                if(strA.ToUpper().Equals(strB.ToUpper()))

                {

                }

                if(string.Equals(strA.ToUpper(),strB.ToUpper()))

                {

                }

                if(string.Compare(strA,strB,true)==0)

                {

}

    使用FxCop检测出来前边三种都违反了一个叫做Avoid Unnecessary String Creation 的规则,另外,据我们的测试,即使是最后一种也违反了一条Specify CultureInfo 的规则,那么完整的写法是加上CultrueInfo 以后的,如下所示:

       if(string.Compare(strA,strB,true,new System.Globalization.CultureInfo("en-US"))==0)

                {

                }

但是,PM建议CultrueInfo的不要去理会,因为CultrueInfo默认读取的系统格式,而且任何短期的项目都不是支持国际化的,当然产品除外(就像SAP)。

 

2、字符串判断为空的方法

印象中看到过的版本也比较多,例如下边4个:

if(strA == null)

                {

                }

if(strA == "")

                {

                }

                if(strA == string.Empty)

                {

                }

                if(strA.Length == 0)

                {

                }

但是完整的可靠的方式是什么呢?根据FxCop的建议,结论如下:

if(strA == null || strA.Length == 0)

                {

                }

具体什么原因就不解释了,比较简单了。

 

Feedback

#1楼    回复  引用  查看    

2005-03-11 18:28 by 不至于      
Length
判断速度最快把

#2楼    回复  引用  查看    

2005-03-11 18:28 by 不至于      
今天咋没用e文呢

#3楼 [楼主]   回复  引用  查看    

2005-03-11 19:15 by 柚子男      
The focus is not on the speed, but on security or called safety.

If you only use strA.Length as a condition, when the strA is null, you will encounter a exception. It is just like NullReferenceException.

so the best choice is
if(strA == null || strA.Length == 0)


#4楼    回复  引用  查看    

2005-03-12 12:12 by Allen Lee      
Those who want to know why FxCop recommends we should use the following code

if (strA == null || strA.Length == 0)

to see whether a string is empty can also read my article '如何判断字符串是否为空串?[C#]' (http://www.cnblogs.com/allenlooplee/archive/2004/11/11/62805.aspx).

Hope that helps!

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2005-03-11 16:15 编辑过


相关链接:

历史上的今天:
2004-03-11 这个代码是为了实现Value Object???