TypeDescriptor CanConvertFrom Bug?或者我做错了?

Mic*_* T. 1 c# system

这是从http://dnpextensions.codeplex.com/中取出的扩展方法.

我理解字符串"test"不是数字字符串......

我知道GetConverter(targetType)的类型是int ...

我不明白为什么它说它可以从一个字符串转换...但它失败了...

/// <summary>
///     Converts an object to the specified target type or returns the default value.
/// </summary>
/// <typeparam name = "T"></typeparam>
/// <param name = "value">The value.</param>
/// <param name = "defaultValue">The default value.</param>
/// <returns>The target type</returns>
public static T ConvertTo<T>(this object value, T defaultValue)
{
    if (value != null)
    {
        var targetType = typeof(T);
        var valueType = value.GetType();

        if (valueType == targetType) return (T)value;

        var converter = TypeDescriptor.GetConverter(value);
        if (converter != null)
        {
            if (converter.CanConvertTo(targetType))
                return (T)converter.ConvertTo(value, targetType);
        }

        converter = TypeDescriptor.GetConverter(targetType);
        if (converter != null)
        {
            if (converter.CanConvertFrom(valueType))
                return (T)converter.ConvertFrom(value);
        }
    }
    return defaultValue;
}
Run Code Online (Sandbox Code Playgroud)
    [TestMethod]
    public void TestConvertToWillFail()
    {
        // Arrange
        var value = "test";

        // Act
        var result = value.ConvertTo<int>();

        // Assert
        result.Should().Equal(0);
        result.Should().Not.Equal(value);
    }

    [TestMethod]
    public void TestConvertToShouldPass()
    {
        // Arrange
        var value = 123;
        var stringValue = "123";

        // Act
        var stringResult = stringValue.ConvertTo<int>();

        // Assert
        stringResult.Should().Equal(value);
        stringResult.Should().Not.Equal(0);
    }
Run Code Online (Sandbox Code Playgroud)

注意:Should()来自Should.codeplex.com


测试例外:

test不是Int32的有效值.

SWe*_*eko 6

你的方法在第二次调用中所做的是:

  • 获取StringConverter
  • 问它是否可以转换为整数 - 它回答
  • 获取IntegerConverter
  • 问它是否可以从字符串转换 - 它回答
  • 要求它转换提供的值("test") - 这就是它爆炸的地方,因为"test"确实不是Int32的有效值.

这些CanConvertFrom/To方法只是验证调用是否有意义,而不是转换是否成功,因为CanConvert只能在类型级别上工作

有些字符串将转换为有效的整数,但这并不意味着所有字符串都是有效的整数,因此ConvertFrom/To即使CanConvert返回true ,也会抛出异常.