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](片段):
public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>
...{
static String()
...{
string.Empty = "";
// Code here
}
// Code here
public static readonly string Empty;
public static bool operator ==(string a, string b)
...{
return string.Equals(a, b);
}
public static bool Equals(string a, string b)
...{
if (a == b)
...{
return true;
}
if ((a != null) && (b != null))
...{
return string.EqualsHelper(a, b);
}
return false;
}
private static unsafe bool EqualsHelper(string ao, string bo)
...{
// Code here
int num1 = ao.Length;
if (num1 != bo.Length)
...{
return false;
}
// Code here
}
private extern int InternalLength();
public int Length
...{
get
...{
return this.InternalLength();
}
}
// Code here
}