从“System.Int32”到“System.Nullable”1[[System.Int32, mscorlib]]

本文关键字:System Int32 mscorlib Nullable | 更新日期: 2023-09-27 18:25:52

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

我在上面的代码中得到了无效的投射异常。对于上面,我可以简单地编写int? nVal = val,但上面的代码是动态执行的。

正在获取一个值(不可为空的类型,如 int、float 等(包装在一个对象(这里是 val(中,我必须通过将其转换为另一种类型(它可以或不能是可为空的版本(来将其保存到另一个对象。什么时候

从"System.Int32"到"System.Nullable"1[[System.Int32, mscorlib, 版本=4.0.0.0, 区域性=中性, PublicKeyToken=b77a5c561934e089]]'.

一个int,应该是可转换/类型铸造到nullable int,这里有什么问题?

从“System.Int32”到“System.Nullable”1[[System.Int32, mscorlib]]

您必须

使用 Nullable.GetUnderlyingType 来获取底层类型的Nullable

这是我用来克服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);
}

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

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

int? unVal = (int)val;

您可以使用Nullable.GetUnderlyingType方法。

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

泛型类型定义是一个类型声明,例如 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.

我想我应该解释为什么这个函数不起作用:

1-引发异常的行如下所示:

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

实际上,函数在数组 Convert.ConvertType 中搜索之后,它会查看 targer 是否是枚举,当找不到任何内容时,它会抛出上面的异常。

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?不在 ConvertType 数组中,也不是枚举,因此会引发异常。

因此,要

恢复,要使函数Convert.ChnageType正常工作,您有:

  1. 要转换的对象是可转换的

  2. 目标类型在转换类型中,而不是Empty也不是DBNull(对这两个类型进行了显式测试,但有抛出异常(

此行为是因为int(和所有其他默认类型(使用Convert.DefaultToType作为 IConvertibale。ToType implementation. and here is the code of the DefaultToType extracted使用 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;
}
相关文章: