我正在使用反射,并且我想对异常处理进行转换检查。
我需要检查字符串是否可以在我的项目中转换为未知类型。
我用过:
TypeConverter t = TypeDescriptor.GetConverter(typeof(string));
Console.WriteLine(t.CanConvertTo(typeof(int)));
但它返回 false!
或者甚至这个又返回 false :
StringConverter stringConverter = new StringConverter();
Console.WriteLine(stringConverter.CanConvertTo(typeof(int)));
我的问题是为什么 StringConverter 将字符串转换为 int 时返回 false ???
编辑:
我使用此代码将字符串转换为未知类型:(结果是字符串)
resultCastedToTargetPropertyType = Convert.ChangeType(result,propertyInfo.PropertyType);
最佳答案
除了 CanConvertFrom
实现的奇怪之处之外,在您的上下文中,在您尝试之前,知道可以执行某种转换不会获得太多帮助。转换器无法仅根据类型为您提供明确的答案,出于同样的原因,对于“字符串是否可以转换为整数”这个问题没有单一的答案:答案是“它取决于字符串” - 即字符串"123"
可以转换为 int
,而字符串 "hello"
和 "1234567891011121314151617181920"
不能转换为int
。
也就是说,只有知道被转换的值才能得到答案。在您的情况下,这意味着在您对 Convert.ChangeType
的调用周围放置 try
/catch
block ,并解释它可能抛出的四个异常中的每一个( reference)。
关于c# - 检查字符串类型到其他类型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533178/