88
Type t = typeof(int?); //will get this dynamically
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, t);//getting exception here

我在上面的代码中得到 InvalidCastException。对于上面我可以简单地写int? nVal = val,但上面的代码是动态执行的。

我得到一个值(不可为空的类型,如 int、float 等)包裹在一个对象(此处为 val)中,我必须通过将其转换为另一种类型(可以或不能是可空版本)将其保存到另一个对象其中)。什么时候

从 'System.Int32' 到 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'的无效转换。

一个int, 应该可以转换/类型转换为nullable int,这里有什么问题?

4

3 回答 3

161

您必须使用Nullable.GetUnderlyingType来获取Nullable.

这是我用来克服 for 限制的ChangeType方法Nullable

public static T ChangeType<T>(object value) 
{
   var t = typeof(T);

   if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
   {
       if (value == null) 
       { 
           return default(T); 
       }

       t = Nullable.GetUnderlyingType(t);
   }

   return (T)Convert.ChangeType(value, t);
}

非通用方法:

public static object ChangeType(object value, Type conversion) 
{
   var t = conversion;

   if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
   {
       if (value == null) 
       { 
           return null; 
       }

       t = Nullable.GetUnderlyingType(t);
   }

   return Convert.ChangeType(value, t);
}
于 2013-08-02T11:19:09.783 回答
11

对于上面我可以简单地写 int? nVal = 值

实际上,你也不能这样做。没有从objectto的隐式转换Nullable<int>。但是有一个隐式转换 from inttoNullable<int>所以你可以这样写:

int? unVal = (int)val;

你可以使用Nullable.GetUnderlyingType方法。

返回指定可为空类型的基础类型参数

泛型类型定义是一种类型声明,例如 Nullable,它包含一个类型参数列表,并且类型参数列表声明一个或多个类型参数。封闭的泛型类型是一种类型声明,其中为类型参数指定了特定类型。

Type t = typeof(int?); //will get this dynamically
Type u = Nullable.GetUnderlyingType(t);
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, u);// nVal will be 5

这是一个DEMO.

于 2013-08-02T11:16:07.413 回答
2

我想我应该解释一下为什么该功能不起作用:

1-引发异常的行如下:

throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", new object[]
  {
    value.GetType().FullName, 
    targetType.FullName
    }));

事实上,在数组 Convert.ConvertTypes 中搜索函数之后,它会查看目标是否是 Enum,当没有找到任何内容时,它会抛出上面的异常。

2- Convert.ConvertTypes 被初始化为:

Convert.ConvertTypes = new RuntimeType[]
   {
      (RuntimeType)typeof(Empty), 
      (RuntimeType)typeof(object), 
      (RuntimeType)typeof(DBNull), 
      (RuntimeType)typeof(bool), 
      (RuntimeType)typeof(char), 
      (RuntimeType)typeof(sbyte), 
      (RuntimeType)typeof(byte), 
      (RuntimeType)typeof(short), 
      (RuntimeType)typeof(ushort), 
      (RuntimeType)typeof(int), 
      (RuntimeType)typeof(uint), 
      (RuntimeType)typeof(long), 
      (RuntimeType)typeof(ulong), 
      (RuntimeType)typeof(float), 
      (RuntimeType)typeof(double), 
      (RuntimeType)typeof(decimal), 
      (RuntimeType)typeof(DateTime), 
      (RuntimeType)typeof(object), 
      (RuntimeType)typeof(string)
   };

因此,由于int?不在 ConvertTypes 数组中,也不是 Enum ,因此会引发异常。

所以要恢复,要让函数 Convert.ChnageType 工作,你有:

  1. 要转换的对象是 IConvertible

  2. 目标类型在 ConvertTypes 中,而不是Emptynor DBNull(对这两个有一个明确的测试,抛出异常)

此行为是因为int(和所有其他默认类型)Convert.DefaultToType用作 IConvertibale.ToType implementation. and here is the code of theDefaultToTypeextracted使用ILSpy

internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
{
    if (targetType == null)
    {
        throw new ArgumentNullException("targetType");
    }
    RuntimeType left = targetType as RuntimeType;
    if (left != null)
    {
        if (value.GetType() == targetType)
        {
            return value;
        }
        if (left == Convert.ConvertTypes[3])
        {
            return value.ToBoolean(provider);
        }
        if (left == Convert.ConvertTypes[4])
        {
            return value.ToChar(provider);
        }
        if (left == Convert.ConvertTypes[5])
        {
            return value.ToSByte(provider);
        }
        if (left == Convert.ConvertTypes[6])
        {
            return value.ToByte(provider);
        }
        if (left == Convert.ConvertTypes[7])
        {
            return value.ToInt16(provider);
        }
        if (left == Convert.ConvertTypes[8])
        {
            return value.ToUInt16(provider);
        }
        if (left == Convert.ConvertTypes[9])
        {
            return value.ToInt32(provider);
        }
        if (left == Convert.ConvertTypes[10])
        {
            return value.ToUInt32(provider);
        }
        if (left == Convert.ConvertTypes[11])
        {
            return value.ToInt64(provider);
        }
        if (left == Convert.ConvertTypes[12])
        {
            return value.ToUInt64(provider);
        }
        if (left == Convert.ConvertTypes[13])
        {
            return value.ToSingle(provider);
        }
        if (left == Convert.ConvertTypes[14])
        {
            return value.ToDouble(provider);
        }
        if (left == Convert.ConvertTypes[15])
        {
            return value.ToDecimal(provider);
        }
        if (left == Convert.ConvertTypes[16])
        {
            return value.ToDateTime(provider);
        }
        if (left == Convert.ConvertTypes[18])
        {
            return value.ToString(provider);
        }
        if (left == Convert.ConvertTypes[1])
        {
            return value;
        }
        if (left == Convert.EnumType)
        {
            return (Enum)value;
        }
        if (left == Convert.ConvertTypes[2])
        {
            throw new InvalidCastException(Environment.GetResourceString("InvalidCast_DBNull"));
        }
        if (left == Convert.ConvertTypes[0])
        {
            throw new InvalidCastException(Environment.GetResourceString("InvalidCast_Empty"));
        }
    }
    throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", new object[]
    {
        value.GetType().FullName, 
        targetType.FullName
    }));
}

另一方面,强制转换由 Nullable 类本身实现,定义为:

public static implicit operator T?(T value)
{
    return new T?(value);
}
public static explicit operator T(T? value)
{
    return value.Value;
}
于 2013-08-02T11:40:58.617 回答