.NET Core 2.0.5中ushort的TypeConverter异常提示Int16原因咨询
关于.NET Core 2.0.5中ushort类型转换器错误信息显示异常的问题
这确实是.NET Core 2.x版本里一个挺让人困惑的小bug,我之前帮同事排查类似问题时也碰到过一模一样的情况——当用TypeConverter处理ushort(也就是UInt16)类型的无效转换时,抛出的FormatException错误信息会错误地指向Int16,但其他数值类型(比如decimal、double、int这些)的错误提示都能正常显示对应的类型名称。
复现你的测试场景
你提到的失败单元测试可以完整写出来,方便大家复现这个问题:
using System; using System.ComponentModel; using Xunit; public class UshortTypeConverterTests { [Fact] public void UshortTypeConverter_InvalidInput_ThrowsIncorrectExceptionMessage() { var converter = TypeDescriptor.GetConverter(typeof(ushort)); // 传入无效字符串,触发转换失败 converter.ConvertFromString("badvalue"); } }
运行这个测试后,抛出的异常信息确实是:
badvalue is not a valid value for Int16.
问题原因与解决办法
这个问题在后续的.NET Core版本(比如3.0及以上)以及.NET 5+中已经被官方修复了。所以最直接的解决方式,如果你的项目允许升级框架版本,直接升级到较新的.NET Core/.NET版本就能彻底解决这个错误信息显示错误的问题。
如果暂时没办法升级框架,你可以通过自定义TypeConverter来覆盖ushort的默认转换逻辑,在捕获异常时手动修正错误信息:
public class CustomUInt16TypeConverter : TypeConverter { private readonly TypeConverter _baseConverter = TypeDescriptor.GetConverter(typeof(ushort)); public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return _baseConverter.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { try { return _baseConverter.ConvertFrom(context, culture, value); } catch (FormatException ex) { // 把错误信息里的Int16替换成正确的UInt16 throw new FormatException(ex.Message.Replace("Int16", "UInt16"), ex.InnerException); } } }
然后在项目启动或者使用转换器之前,注册这个自定义转换器:
// 注册自定义转换器,覆盖ushort的默认转换器 TypeDescriptor.AddAttributes(typeof(ushort), new TypeConverterAttribute(typeof(CustomUInt16TypeConverter)));
这样再运行测试时,错误信息就会正确显示为:
badvalue is not a valid value for UInt16.
内容的提问来源于stack exchange,提问作者pseudobjorn
相关产品推荐
相关产品推荐

