[英]asp.net master property string, how to check in content page if string is empty
if i have a master property string for example: 如果我有一个主属性字符串,例如:
public String SharedInfo
{
get { return (String)Session["SharedInfo"]; }
set { Session["SharedInfo"] = value; }
}
and a label in an content page, i check if the string is empty by doing: if(Master.SharedInfo == null) 和内容页面中的标签,我通过执行以下操作检查字符串是否为空:if(Master.SharedInfo == null)
now my question is: why does if(Master.SharedInfo == "") not work, because the SharedInfo is a string right? 现在我的问题是:为什么if(Master.SharedInfo ==“”)不起作用,因为SharedInfo是一个字符串,对吗?
There is a handy method that "catches" both 有一种方便的方法可以“捕捉”两个
if (String.IsNullOrEmpty(Master.SharedInfo)) {
...
}
null
and ""
are not equal. null
和""
不相等。 null
means no string at all. null
表示完全没有字符串。 ""
is a string of length 0
. ""
是长度为0
的字符串。
string s = null;
int i = s.Length; // <-- Throws null reference exception
But 但
string s = "";
int i = s.Length; // OK, i => 0
""
and String.Empty
are equivalent. ""
和String.Empty
是等效的。 Some people state that you should always use String.Empty
instead of ""
, but it makes really no difference. 有人指出您应该始终使用
String.Empty
而不是""
,但这实际上没有什么区别。
UPDATE UPDATE
Equal string constants are interned by the compiler, ie the compiler stores equal constants only once. 相等的字符串常量由编译器插入,即,编译器仅存储一次相等的常量。 You can make a simple test (in response to @BobTodd's comment),
您可以进行简单的测试(以回应@BobTodd的评论),
string s = "";
Console.WriteLine(Object.ReferenceEquals(s, "")); // --> true
Console.WriteLine(Object.ReferenceEquals(s, String.Empty)); // --> true
For the sake of completeness (according to @JoelEtherton's comment). 为了完整起见(根据@JoelEtherton的评论)。 Starting from .NET Framework 4.0 you can test
从.NET Framework 4.0开始,您可以进行测试
if (String.IsNullOrWhitespace(Master.SharedInfo)) {
...
}
This will catch strings like " "
or "\\t"
as well. 这也将捕获类似
" "
或"\\t"
字符串。
In c#, an empty string ""
is not null. 在c#中,空字符串
""
不为null。 It's an actual string, with length equals to zero. 这是一个实际的字符串,长度等于零。
You can use string.IsNullOrEmpty(string stringToTest)
to check both null and empty strings. 您可以使用
string.IsNullOrEmpty(string stringToTest)
来检查空字符串和空字符串。
String.Empty
("") and null
are quite different String.Empty
(“”)和null
完全不同
It depends wholly on what has been written to Session["SharedInfo"]. 这完全取决于已写入Session [“ SharedInfo”]的内容。
If nothing has, then it will be null, otherwise its the value written, which could be an empty string or null. 如果没有任何内容,则它将为null,否则将为其写入的值,该值可以为空字符串或null。
To be sure use String.IsNullOrEmpty(string @string)
确保使用
String.IsNullOrEmpty(string @string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.