ins*_*ite 50 c# coding-style tryparse isnumeric request.querystring
我经常使用Request.QueryString[]变量.
在我Page_load经常做的事情:
int id = -1;
if (Request.QueryString["id"] != null) {
try
{
id = int.Parse(Request.QueryString["id"]);
}
catch
{
// deal with it
}
}
DoSomethingSpectacularNow(id);
Run Code Online (Sandbox Code Playgroud)
这一切似乎有点笨拙和垃圾.你怎么处理你Request.QueryString[]的?
Bry*_*tts 52
下面是一个扩展方法,允许您编写如下代码:
int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");
Run Code Online (Sandbox Code Playgroud)
它TypeDescriptor用于执行转换.根据您的需要,您可以添加一个重载,该重载采用默认值而不是抛出异常:
public static T GetValue<T>(this NameValueCollection collection, string key)
{
if(collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if(value == null)
{
throw new ArgumentOutOfRangeException("key");
}
var converter = TypeDescriptor.GetConverter(typeof(T));
if(!converter.CanConvertFrom(typeof(string)))
{
throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
}
return (T) converter.ConvertFrom(value);
}
Run Code Online (Sandbox Code Playgroud)
VVS*_*VVS 34
使用int.TryParse来取消try-catch块:
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}
Run Code Online (Sandbox Code Playgroud)
Aut*_*ion 19
试试这个家伙......
List<string> keys = new List<string>(Request.QueryString.AllKeys);
Run Code Online (Sandbox Code Playgroud)
然后你就可以通过...搜索这个家伙了.
keys.Contains("someKey")
Run Code Online (Sandbox Code Playgroud)
M4N*_*M4N 17
我正在使用一个小帮手方法:
public static int QueryString(string paramName, int defaultValue)
{
int value;
if (!int.TryParse(Request.QueryString[paramName], out value))
return defaultValue;
return value;
}
Run Code Online (Sandbox Code Playgroud)
此方法允许我以下列方式从查询字符串中读取值:
int id = QueryString("id", 0);
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
好吧,有一件事使用int.TryParse而不是......
int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
id = -1;
}
Run Code Online (Sandbox Code Playgroud)
这假设"不存在"应该与"非整数"当然具有相同的结果.
编辑:在其他情况下,当你打算将请求参数用作字符串时,我认为验证它们是否存在肯定是一个好主意.
您也可以使用下面的扩展方法,并执行此操作
int? id = Request["id"].ToInt();
if(id.HasValue)
{
}
Run Code Online (Sandbox Code Playgroud)
//扩展方法
public static int? ToInt(this string input)
{
int val;
if (int.TryParse(input, out val))
return val;
return null;
}
public static DateTime? ToDate(this string input)
{
DateTime val;
if (DateTime.TryParse(input, out val))
return val;
return null;
}
public static decimal? ToDecimal(this string input)
{
decimal val;
if (decimal.TryParse(input, out val))
return val;
return null;
}
Run Code Online (Sandbox Code Playgroud)