<分区>
我必须验证用户输入数据并确保字符串值可转换为运行时指定的类型。我不一定需要进行实际转换,只需测试以确保输入值有效即可。我还没有找到可以执行此类评估的内置类或方法,但如果我遗漏了一个,请告诉我。如果有任何版本特定的解决方案可用,我正在使用 C#4.0。
该方法只需要处理“标准”类型(内置值数据类型加上字符串)。我唯一需要评估的自定义类型是库中定义的特定枚举类型。
我目前正在权衡 2 个解决方案,但都不是完美的,所以我希望有第三个选项(或者我错过的框架内置的东西)。我非常倾向于解决方案 #2,因为在解决方案 #1 中使用 try-catch 似乎是错误的。
解决方案 1:Convert.ChangeType()
与 try/catch
public Boolean CheckType(String value, Type type)
{
try
{
var obj = Convert.ChangeType(value, type);
return true;
}
catch(InvalidCastException)
{
return false;
}
catch(FormatException)
{
return false;
}
catch(OverflowException)
{
return false;
}
catch(ArgumentNullException)
{
return false;
}
}
解决方案 2 带类型检查和 TryParse 的 if/else 链
public Boolean CheckType(String value, Type type)
{
if (type == typeof(String))
{
return true;
}
else if (type == typeof(Boolean))
{
Boolean b;
return Boolean.TryParse(value, out b);
}
else if (type == typeof(Int32))
{
Int32 i;
return Int32.TryParse(value, out i);
}
else if (type == typeof(Int64))
{
Int64 l;
return Int64.TryParse(value, out l);
}
// similar code to check all other types
// (Int16, UInt32, UInt64, UInt16, Byte, SByte, Single, Double, Decimal,
// Enum, Char, DateTime)
.
.
.
.
.
else
throw new ArgumentException("Invalid type evaluation");
}
如果输入数据严重困惑或损坏,此方法可能会在短时间内被调用数百次甚至上千次,因此我担心重复的 if/else 检查会拖累性能(我我现在不一定要尝试优化,我只是想确保我正在考虑其他选项)。
我对这两种解决方案的另一个问题是,它们实际上都将字符串值转换为预期类型的新值,并且在这两种情况下,我都接受了结果。