这是从http://dnpextensions.codeplex.com/中取出的扩展方法。TypeDescriptor CanConvertFrom Bug?或者我做错了?
据我所知,字符串“测试”是不是一个数字串...
据我所知,GetConverter(目标类型)的类型为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;
}
[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);
}
注意事项:应()从S hould.codeplex.com从测试
例外:
测试不是的Int32的有效值。
其实我只是发现StringConverter不会转换为整数,而是IntegerConverter从字符串转换。有点奇怪,但事情就是这样。 – SWeko 2010-12-15 09:46:37
@Sekeko:有趣的是,'StringConverter'只能转换字符串和从字符串转换; P – leppie 2010-12-16 07:54:10