我正在使用 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/