[英]set property of master page from content page and get that property value from another content page in asp.net
[英]asp.net master property string, how to check in content page if string is empty
如果我有一个主属性字符串,例如:
public String SharedInfo
{
get { return (String)Session["SharedInfo"]; }
set { Session["SharedInfo"] = value; }
}
和内容页面中的标签,我通过执行以下操作检查字符串是否为空:if(Master.SharedInfo == null)
现在我的问题是:为什么if(Master.SharedInfo ==“”)不起作用,因为SharedInfo是一个字符串,对吗?
有一种方便的方法可以“捕捉”两个
if (String.IsNullOrEmpty(Master.SharedInfo)) {
...
}
null
和""
不相等。 null
表示完全没有字符串。 ""
是长度为0
的字符串。
string s = null;
int i = s.Length; // <-- Throws null reference exception
但
string s = "";
int i = s.Length; // OK, i => 0
""
和String.Empty
是等效的。 有人指出您应该始终使用String.Empty
而不是""
,但这实际上没有什么区别。
UPDATE
相等的字符串常量由编译器插入,即,编译器仅存储一次相等的常量。 您可以进行简单的测试(以回应@BobTodd的评论),
string s = "";
Console.WriteLine(Object.ReferenceEquals(s, "")); // --> true
Console.WriteLine(Object.ReferenceEquals(s, String.Empty)); // --> true
为了完整起见(根据@JoelEtherton的评论)。 从.NET Framework 4.0开始,您可以进行测试
if (String.IsNullOrWhitespace(Master.SharedInfo)) {
...
}
这也将捕获类似" "
或"\\t"
字符串。
在c#中,空字符串""
不为null。 这是一个实际的字符串,长度等于零。
您可以使用string.IsNullOrEmpty(string stringToTest)
来检查空字符串和空字符串。
String.Empty
(“”)和null
完全不同
这完全取决于已写入Session [“ SharedInfo”]的内容。
如果没有任何内容,则它将为null,否则将为其写入的值,该值可以为空字符串或null。
确保使用String.IsNullOrEmpty(string @string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.