c# - 为什么 TypeConverter 为 ushort 类型返回的 FormatException 引用 Int16?

标签 c# .net-core typeconverter

我正在使用 C# 和 .NET Core 2.0.5 编写代码。当对 ushort 类型使用 TypeConverter 并且转换失败时,FormatException 消息引用 Int16,而不是 UInt16。谁能给我解释一下?

我测试过的其他类型(十进制、 double 、 float 、整数、长整型、短整型、uint、ulong)在错误消息中返回预期的类型名称。

为了表明我的观点,这是一个会失败的单元测试。错误消息显示“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);
        }
    }

这是测试的输出:

Expected: ···t a valid value for UInt16.

Actual: ···t a valid value for Int16.

最佳答案

这是 UInt16Converter(您使用 TypeDescriptor.GetConverter(typeof(ushort)) 返回的类型)中的错误。具体来说,this line:

internal override Type TargetType => typeof(short);

显然应该读作 ushort 而不是 short。此错误是作为 cleanup commit 的一部分引入的使用 expression-bodied 成员。

异常消息似乎是唯一受影响的东西。转换为字符串时,它还会在 TypeConverter.ConvertTo 中选择一个略有不同的代码路径,但这对 UInt16 值的格式没有实际影响。请注意 tests对于这个类不包括这个:他们只验证 ConvertFrom 抛出一个无效值,而不是什么类型的异常,或消息的内容。 (后者几乎肯定是设计使然,因为 .NET 异常消息已本地化。)

关于c# - 为什么 TypeConverter 为 ushort 类型返回的 FormatException 引用 Int16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361595/

相关文章:

c# - 如何在 Windows 机器上为 Linux 编译 .NET Core 应用程序

java - Spring转换器将null转换为空集合

Javascript按位转c#

c# - 在两个日期范围之间相交的天数

c# - 如何在 C# 库中使用嵌入式 .NET exe,而不从其 byte[] 重建文件?

asp.net - OpenIddict - 在同一项目中托管身份验证服务器和 Web api 资源

Azure ServiceBusQueue 函数未在本地触发

类似于 Masonry 的 C# 网格布局库

c# - 类型转换器因原始类型而损坏?

c# - Automapper - 如何使用 automapper 将三个实体映射到一个实体?