我已经习惯使用TryParse来尝试解析未知类型:
Dim b As Boolean
Dim qVal As Boolean = If(Boolean.TryParse(Request.QueryString("q").Trim(), b), b, False)
Run Code Online (Sandbox Code Playgroud)
要么
bool b;
bool qVal = (Boolean.TryParse(Request.QueryString("q").Trim(), out b) ? b : false;
Run Code Online (Sandbox Code Playgroud)
所以,只是好奇是否有人知道除了使用三元运算符之外更好的方法.
再次问好,
由于帖子已经关闭,我确信这个解决方案会被埋没在那里,但我创建了一个非常酷的类,使用我给出的建议解决了上面的问题.只是想把代码放在那里以防万一有人偶然发现这个线程并想使用它:
public static class PrimitiveType
{
/// <summary>
/// This function will return a parsed value of the generic type specified.
/// </summary>
/// <typeparam name="valueType">Type you are expecting to be returned</typeparam>
/// <param name="value">String value to be parsed</param>
/// <param name="defaultValue">Default value in case the value is not parsable</param>
/// <returns></returns>
public static valueType ParseValueType<valueType>(string value, valueType defaultValue)
{
MethodInfo meth = typeof(valueType).GetMethod("Parse", new Type[] { typeof(string) });
if (meth != null)
{
try
{
return (valueType) meth.Invoke(null, new object[] { value });
}
catch (TargetInvocationException ex)
{
if (ex.InnerException.GetType() == typeof(FormatException) || ex.InnerException.GetType() == typeof(OverflowException))
{
return defaultValue;
}
else throw ex.InnerException;
}
}
else
{
throw new ArgumentException("Generic type must be a valid Value Type that has a Parse method.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
它使用起来非常简单.只需将您期望的类型作为泛型传递,并提供要解析的字符串值,并在字符串不可解析时提供默认值.如果你提供一个类而不是一个原始类型throw new ArgumentException("Generic type must be a valid Value Type that has a Parse method.");
我之前在自己的课堂上包含了查询字符串.然后我可以做类似以下的事情:
var qs = new QueryString(Request.QueryString);
bool q = qs.Get<bool>("q");
Run Code Online (Sandbox Code Playgroud)