为什么Convert.ChangeType带有对象参数? [英] Why does Convert.ChangeType take an object parameter?

查看:120
本文介绍了为什么Convert.ChangeType带有对象参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转换 类自.NET 1.0开始就存在。 IConvertible 接口。

The Convert class has been in existence since .NET 1.0. The IConvertible interface has also existed since this time.

Convert.ChangeType 方法 only 对实现 IConvertible的类型的对象有效(实际上,除非我弄错了, Convert 类提供的 all 都是这种方法)。那么为什么参数类型为 object

The Convert.ChangeType method only works on objects of types that implement IConvertible (in fact, unless I'm mistaken, all of the conversion methods provided by the Convert class are this way). So why is the parameter type object?

换句话说,而不是:

public object ChangeType(object value, Type conversionType);

为什么不签名呢?

public object ChangeType(IConvertible value, Type conversionType);

对我来说似乎很奇怪。

推荐答案

在反射器中,您可以看到 ChangeType(object,Type,IFormatProvider)的顶部,这是幕后的内容:

Looking in reflector you can see the top of ChangeType(object, Type, IFormatProvider), which is what's called under the covers:

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 ,但已经了,目标类型将只返回原始对象。

So it looks like an object of a type that doesn't implement IConvertible but already is the destination type will just return the original object.

当然,这似乎是需要实现 IConvertible only 例外>,但这是一个例外,它看起来像是参数改为 object 的原因。

Granted it looks like this is the only exception to the value needing to implement IConvertible, but it is an exception, and looks like the reason the parameter is object instead.

以下是此情况的快速LinqPad测试:

Here's a quick LinqPad test for this case:

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;
}

这篇关于为什么Convert.ChangeType带有对象参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆