[英]How better check Request.QueryString string parameter for null?
我需要解釋..我將C#.NET用於Web應用程序,我總是這樣寫:
string val = Request.QueryString["foo"];
然后
if(!string.IsNullOrEmpty(val))
有什么不同:
string val = Request.QueryString["foo"];
我被建議做:
string val = Request.QueryString["foo"] as string;
if(!string.IsNullOrEmpty(val))
有什么不同?
第一個更好:
string val = Request.QueryString["foo"];
如果調用的結果不是字符串,則第二個版本返回null
,但是您知道它始終是一個字符串,因為QueryString
成員的類型為NameValueCollection
。 索引器被定義為返回一個string
:
public class NameValueCollection : NameObjectCollectionBase
{
// ...
public string this[string name] { get; set; }
// ...
}
as string
是冗余的,因為Request.QueryString["foo"]
已經是一個字符串。 (所以沒有其他區別,第二個讓你看起來像你不知道你的框架;-))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.