如果您一直在寻找一种漂亮而干净的方法来解析查询字符串值,我已经想到了这个方法:
/// <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);
}
我一直想要这样的东西,最终终于搞定了...至少我是这么认为的...
代码应该是自解释的...
欢迎提出任何意见或建议以使其更好。