gpt4 book ai didi

.net - 为什么 Convert.ChangeType 采用对象参数?

转载 作者:行者123 更新时间:2023-12-04 12:00:44 25 4
gpt4 key购买 nike

Convert 自 .NET 1.0 起就存在类。 IConvertible 从那时起,界面也已经存在。

Convert.ChangeType 方法仅适用于实现 IConvertible 的类型的对象(事实上​​,除非我弄错了,Convert 类提供的所有转换方法都是这样的)。那么为什么参数类型是object ?

换句话说,而不是这样:

public object ChangeType(object value, Type conversionType);

为什么不是这个签名?
public object ChangeType(IConvertible value, Type conversionType);

对我来说似乎很奇怪。

最佳答案

从反射器中可以看到 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;
}

所以它看起来像一个没有实现 IConvertible 的类型的对象但已经是目标类型将只返回原始对象。

当然,这似乎是实现 IConvertible 所需值的唯一异常(exception)。 ,但它是一个异常(exception),看起来参数是 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;
}

关于.net - 为什么 Convert.ChangeType 采用对象参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com