为什么TypeHverter为ushort类型返回的FormatException引用Int16?

pse*_*orn 5 c# typeconverter .net-core

我在C#和.NET Core 2.0.5中编写代码.对于ushort类型使用TypeConverter并且转换失败时,FormatException-message引用Int16而不是UInt16.任何人都可以向我解释这个吗?

我测试的其他类型(decimal,double,float,int,long,short,uint,ulong)在错误消息中返回预期的typename.

为了表明我的观点,这是一个失败的单元测试.错误消息显示"badvalue不是Int16的有效值.".

    [Fact]
    public void FailingToConvertUShort_GivesFormatExceptionMessage_WithCorrectType()
    {
        // Arrange
        var badvalue = "badvalue";
        var typeConverter = TypeDescriptor.GetConverter(typeof(ushort));

        try
        {
            // Act
            var result = typeConverter.ConvertFrom(context: null, culture: new CultureInfo("en-GB"), value: badvalue);
        }
        catch (Exception ex)
        {
            // Assert
            Assert.Equal($"badvalue is not a valid value for {typeof(ushort).Name}.", ex.Message);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是测试的输出:

预期:···用于UInt16的有效值.

实际:···Int16的有效值.

Jer*_*ert 2

这是UInt16Converter( 你用 . 返回的类型)中的一个错误TypeDescriptor.GetConverter(typeof(ushort))。具体来说,这一行

internal override Type TargetType => typeof(short);
Run Code Online (Sandbox Code Playgroud)

显然应该阅读ushort 而不是short. 此错误是作为使用表达式主体成员的清理提交的一部分引入的。

异常消息似乎是唯一受到影响的事情。在转换为字符串时,它还会选择略有不同的代码路径TypeConverter.ConvertTo,但这对值的格式没有实际影响UInt16。请注意,此类的测试不涵盖这一点:它们仅验证是否ConvertFrom抛出无效值,而不验证异常类型或消息的内容。(后者几乎肯定是设计使然,因为 .NET 异常消息是本地化的。)