如果您一直在寻找一种很好且干净的方法来解析查询字符串值,我想出了这个:
/// <summary>
/// Parses the query string and returns a valid value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The query string key.</param>
/// <param name="value">The value.</param>
protected internal T ParseQueryStringValue<T>(string key, string value)
{
if (!string.IsNullOrEmpty(value))
{
//TODO: Map other common QueryString parameters type ...
if (typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(value, typeof(T));
}
if (typeof(T) == typeof(int))
{
int tempValue;
if (!int.TryParse(value, out tempValue))
{
throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
"'{1}' is not a valid {2} type.", key, value, "int"));
}
return (T)Convert.ChangeType(tempValue, typeof(T));
}
if (typeof(T) == typeof(DateTime))
{
DateTime tempValue;
if (!DateTime.TryParse(value, out tempValue))
{
throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
"'{1}' is not a valid {2} type.", key, value, "DateTime"));
}
return (T)Convert.ChangeType(tempValue, typeof(T));
}
}
return default(T);
}
我一直想拥有这样的东西,最后做对了……至少我是这么认为的……
代码应该是不言自明的......
任何使它更好的意见或建议表示赞赏。