クエリ文字列の値を解析するための適切でクリーンな方法を探していた場合は、次の方法を思い付きました。
/// <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);
}
私はいつもそのようなものを持ちたいと思っていましたが、ついにそれがうまくいきました...少なくとも私はそう思います...
コードは自明である必要があります...
より良いものにするためのコメントや提案は大歓迎です。