0. 缘起:
本文写作缘起于阮的讨论——《FxCop告诉我,检查一个字符串是否为空要用string.Length。》。其实用过FxCop的人都知道它会建议你使用String.Length属性来判断字符串是否为空串,但你又是否明白其中的缘由呢?今天有点闲,特意写下这篇文章,希望有点帮助。
1. 三种常用的字符串判空串方法:
Length法:bool isEmpty = (str.Length == 0);
Empty法:bool isEmpty = (str == String.Empty);
General法:bool isEmpty = (str == "");
2. 深入内部机制:
要探讨这三种方法的内部机制,我们得首先看看.NET是怎样实现的,也就是要看看.NET的源代码!然而,我们哪里找这些源代码呢?我们同样有三种方法:
Rotor法:一个不错的选择就是微软的Rotor,这是微软的一个源代码共享项目。
Mono法:另一个不错的选择当然就是真正的开源项目Mono啦!
Reflector法:最后一个选择就是使用反编译器,不过这种重组的代码不一定就是原貌,只不过是一种“近似值”,你可以考虑使用Reflector这个反编译器[1]。
这里我采用Reflector法,我们先来看看一下源代码[2](片段):
CodepublicsealedclassString : IComparable, ICloneable, IConvertible, IEnumerable, IComparable{staticString()
{string.Empty="";//Code here}//Code herepublicstaticreadonlystringEmpty;publicstaticbooloperator==(stringa,stringb)
{returnstring.Equals(a, b);
}publicstaticboolEquals(stringa,stringb)
{if(a==b)
{returntrue;
}if((a!=null)&&(b!=null))
{returnstring.EqualsHelper(a, b);
}returnfalse;
}privatestaticunsafeboolEqualsHelper(stringao,stringbo)
{//Code hereintnum1=ao.Length;if(num1!=bo.Length)
{returnfalse;
}//Code here}privateexternintInternalLength();publicintLength
{get{returnthis.InternalLength();
}
}
}
Rotor里面String类的代码与此没什么不同,只是没有EqualsHelper方法,代之以如下的声明:
publicexternboolEquals(String value);