这是从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的有效值.
你的方法在第二次调用中所做的是:
这些CanConvertFrom/To方法只是验证调用是否有意义,而不是转换是否成功,因为CanConvert只能在类型级别上工作
有些字符串将转换为有效的整数,但这并不意味着所有字符串都是有效的整数,因此ConvertFrom/To即使CanConvert返回true ,也会抛出异常.
| 归档时间: |
|
| 查看次数: |
1423 次 |
| 最近记录: |