Dan*_*Tao 7 .net changetype iconvertible
该Convert自.NET 1.0级已经存在.IConvertible从那时起,界面也存在.
该Convert.ChangeType方法仅适用于实现类型的对象IConvertible(事实上,除非我弄错了,否则类提供的所有转换方法Convert都是这样的).那么为什么参数类型object呢?
换句话说,而不是这样:
public object ChangeType(object value, Type conversionType);
Run Code Online (Sandbox Code Playgroud)
为什么签名不是这个?
public object ChangeType(IConvertible value, Type conversionType);
Run Code Online (Sandbox Code Playgroud)
对我来说似乎很奇怪.
看着反光板,你可以看到顶部ChangeType(object, Type, IFormatProvider),这就是所谓的封面:
public static object ChangeType(object value, Type conversionType, IFormatProvider provider)
{
//a few null checks...
IConvertible convertible = value as IConvertible;
if (convertible == null)
{
if (value.GetType() != conversionType)
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
所以它看起来像一个类型的对象没有实现,IConvertible但已经是目标类型将只返回原始对象.
当然,看起来这是需要实现的值的唯一例外IConvertible,但它是一个例外,看起来就像是参数的原因object.
这是针对此案例的快速LinqPad测试:
void Main()
{
var t = new Test();
var u = Convert.ChangeType(t, typeof(Test));
(u is IConvertible).Dump(); //false, for demonstration only
u.Dump(); //dump of a value Test object
}
public class Test {
public string Bob;
}
Run Code Online (Sandbox Code Playgroud)