为何StringConverter判断字符串转目标类型时返回false?
为什么StringConverter.CanConvertTo(typeof(int))返回false?
嘿,你这是搞反了TypeConverter的转换方向啦!让我给你掰扯清楚:
1. StringConverter的本职工作
StringConverter的设计目标是把其他类型的对象转换成字符串,而不是反过来把字符串解析成其他类型。所以当你调用t.CanConvertTo(typeof(int))时,你其实在问:“这个StringConverter能不能把字符串转换成int?”——但这根本不是它的职责范围,所以它自然返回false。
2. 正确的检查姿势
如果你想判断一个字符串能不能转换成某个未知类型,应该去获取目标类型对应的TypeConverter,然后调用它的CanConvertFrom(typeof(string))方法。举个例子:
// 获取int类型的转换器,它负责处理"从其他类型转成int"的逻辑 TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); // 检查能不能从string转成int Console.WriteLine(intConverter.CanConvertFrom(typeof(string))); // 输出true
3. 补个通用工具方法
如果你的场景是要动态检查任意目标类型,这里有个通用的实现:
public bool CanConvertStringToTargetType(Type targetType) { if (targetType == null) throw new ArgumentNullException(nameof(targetType)); var converter = TypeDescriptor.GetConverter(targetType); return converter != null && converter.CanConvertFrom(typeof(string)); }
简单总结下逻辑:
- 要判断A能不能转成B:找B的TypeConverter,调用
CanConvertFrom(typeof(A)) - 要判断B能不能转成A:找B的TypeConverter,调用
CanConvertTo(typeof(A))
内容的提问来源于stack exchange,提问作者Parsa
相关产品推荐
相关产品推荐

