我需要验证用户输入数据并确保字符串值可以在运行时转换为指定类型。我不一定需要执行实际的转换,只需测试以确保输入值有效。我没有找到内置的类或方法来执行这种类型的评估,但如果我漏掉了一个,请告诉我。我使用C#4.0工作,如果有特定于版本的解决方案可用。
该方法只需处理“标准”类型(内置值数据类型加上String)。我需要评估的唯一自定义类型是库中定义的特定枚举类型。
我目前有两个解决方案,但都不完美,所以我希望有第三个选项(或者是我错过的框架内置功能)。我倾向于解决方案#2,因为在解决方案#1中使用try-catch似乎不太合适。
解决方案1:使用try/catch的Convert.ChangeType()
。
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检查会影响性能(我并不一定要优化,我只想确保我考虑了其他选项)。
我对这两种解决方案的另一个问题是,它们实际上都将字符串值转换为预期类型的新值,在这两种情况下,我都吞掉了结果。