C# 如果不为空,检查查询字符串参数值的最优雅方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11260468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most elegant way of checking the value of a query string parameter if not null?
提问by
if(Page.Request.QueryString["ParamName"] != null)
if(Page.Request.QueryString["ParamName"] == expectedResult)
//Do something spectacular
The above seems cludgey. Is there a more elegant/compact way of checking if a query string parameter is not null and if so - retrieving the value of it?
上面看起来很笨拙。是否有更优雅/紧凑的方法来检查查询字符串参数是否为空,如果是,则检索它的值?
采纳答案by hatchet - done with SOverflow
I thought first of offering
我首先想到了提供
if ((Page.Request.QueryString["ParamName"] ?? "") == expectedResult) {
but quickly realized that with strings, comparing some string with null is fine, and will produce false, so really just using this will work:
但很快意识到,对于字符串,将一些字符串与 null 进行比较是可以的,并且会产生错误,所以实际上只使用它就可以了:
if(Page.Request.QueryString["ParamName"] == expectedResult)
//Do something spectacular
回答by Asif Mushtaq
You can use String.IsNullOrEmpty
您可以使用 String.IsNullOrEmpty
String.IsNullOrEmpty(Page.Request.QueryString["ParamName"]);
Or
或者
var parm = Page.Request.QueryString["ParamName"] ?? "";
if(parm == expectedResult)
{
}
回答by Kane
I personally would go with a simple set of extension methods, something like this:
我个人会使用一组简单的扩展方法,如下所示:
public static class RequestExtensions
{
public static string QueryStringValue(this HttpRequest request, string parameter)
{
return !string.IsNullOrEmpty(request.QueryString[parameter]) ? request.QueryString[parameter] : string.Empty;
}
public static bool QueryStringValueMatchesExpected(this HttpRequest request, string parameter, string expected)
{
return !string.IsNullOrEmpty(request.QueryString[parameter]) && request.QueryString[parameter].Equals(expected, StringComparison.OrdinalIgnoreCase);
}
}
and a sample usage
和示例用法
string value = Page.Request.QueryStringValue("SomeParam");
bool match = Page.Request.QueryStringValueMatchesExpected("SomeParam", "somevaue");

