String.Empty is a static constant of the string class;
String.Empty and string= "" are not very different, because the internal implementation of String.Empty is:
123456789101112 |
public
static
readonly
string
Empty;
//这就是String.Empty 那是只读的String类的成员,也是string的变量的默认值是什么呢?
//String的构造函数
static
String(){
Empty =
""
;
//Empty就是他""
WhitespaceChars =
new
char
[] {
‘\t‘
,
‘\n‘
,
‘\v‘
,
‘\f‘
,
‘\r‘
,
‘ ‘
,
‘\x0085‘
,
‘\x00a0‘
,
‘?‘
,
‘ ‘
,
‘ ‘
,
‘ ‘
,
‘ ‘
,
‘?‘
,
‘?‘
,
‘?‘
,
‘?‘
,
‘?‘
,
‘ ‘
,
‘?‘
,
‘‘
,
‘\u2028‘
,
‘\u2029‘
,
‘ ‘
,
‘‘
};
}
|
Look at the code again:
12345678 |
string
s1 =
""
;
string s2 =
string
.Empty;
if
(s1 == s2)<br>{
Console.WriteLine(
"一模一样!"
);
}
// 结果都是True
Console.WriteLine(
""
.Equals(
string
.Empty));
Console.WriteLine(
object
.ReferenceEquals(
string
.Empty,
""
));
|
Since String.Empty and string= "" also need to occupy memory space, why is it recommended to use String.Empty first?
String. Empty just lets the code read, preventing the code from making ambiguity, such as saying:
string s = ""; string s = ""; It's hard to see whether it's an empty string or a space character.
If a string is judged to be empty, use the
if (S==string.empty) and if (s== "") are the same efficiency, but the most efficient way to do this is if (s.length==0)
String. IsNullOrEmpty's internal implementation method:
public
static bool
IsNullOrEmpty(
string
value)<br>{<br>
if
(value !=
null
)
{
return
(value.Length == 0);
}
return
true
;
}
|
String str=null indicates that STR does not point to any object.
The difference between String.Empty, string= "" and null