如何更好地检查Request.QueryString字符串参数是否为null?

8

我需要解释... 我使用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)) 

什么是不同之处?
2个回答

7
第一个更好:
string val = Request.QueryString["foo"];

第二个版本在调用结果不是字符串时返回null,但是由于QueryString成员的类型是NameValueCollection,你知道它总是返回字符串。索引器被定义为返回一个string
public class NameValueCollection : NameObjectCollectionBase
{
    // ...
    public string this[string name] { get; set; }
    // ...
}

3
< p > “as string”是多余的,因为Request.QueryString["foo"]已经是一个字符串了。这两种写法没有任何区别,但第二种写法会让人觉得你不熟悉你的框架;-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接