mj8*_*j82 5 c# .net-4.0 visual-studio-2010
(求助)我正在构建一个应用程序,它可以根据XML文件中的一些描述动态地创建它的一些控件.
我现在需要的是与TryParse()方法非常相似的东西:如果字符串变量中的文本可以转换(或解析)为一个类型,可以检查(没有抛出/捕获异常),我在其他变量中有这个名称(myType).
问题是myType可以是任何.NET类型:DateTime, Bool, Double, Int32等等.
例:
string testStringOk = "123";
string testStringWrong = "hello";
string myType = "System.Int32";
bool test1 = CanCovertTo(testStringOk, myType); //true
bool test2 = CanCovertTo(testStringWrong, myType); //false
Run Code Online (Sandbox Code Playgroud)
CanCovertTo(string testString, string testType)功能应该如何?
我得到的最接近的是以下代码:
private bool CanCovertTo(string testString, string testType)
{
Type type = Type.GetType(testType, null, null);
TypeConverter converter = TypeDescriptor.GetConverter(type);
converter.ConvertFrom(testString); //throws exception when wrong type
return true;
}
Run Code Online (Sandbox Code Playgroud)
但是,它在尝试从错误的字符串转换时抛出异常,我不想使用try {} catch()它.
解:
private bool CanCovertTo(string testString, string testType)
{
Type type = Type.GetType(testType, null, null);
TypeConverter converter = TypeDescriptor.GetConverter(type);
return converter.IsValid(testString);
}
Run Code Online (Sandbox Code Playgroud)
我会检查方法TypeConverter.IsValid,但是:
从.NET Framework版本4开始,IsValid方法捕获CanConvertFrom和ConvertFrom方法中的异常.如果输入值类型导致CanConvertFrom返回false,或者输入值导致ConvertFrom引发异常,则IsValid方法返回false.
这意味着,如果你不自己使用try ... catch,你将转换两倍的值.
不要将类型作为字符串传入,而应该使用泛型,例如
public bool CanConvert<T>(string data)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
return converter.IsValid(data);
}
Run Code Online (Sandbox Code Playgroud)
用法
bool test1 = CanConvert<Int32>("1234"); // true
bool test2 = CanConvert<Int32>("hello"); // false
Run Code Online (Sandbox Code Playgroud)