C# 使用Int64进行泛型转换

C# 使用Int64进行泛型转换,c#,generics,C#,Generics,我在MySQL连接器中有一个泛型方法,可以进行泛型转换。 我把它简化成一个问题,因为它能产生很多东西。 最后,它进行了一次通用转换,工作正常,但是我在将Int64转换为Int32时遇到了一个问题 object var1 = (long)64; int? var2 = Select<int?>(var1); // ERROR Int32Converter from Int64 public T Select<T>(object value) { return (T)S

我在MySQL连接器中有一个泛型方法,可以进行泛型转换。 我把它简化成一个问题,因为它能产生很多东西。 最后,它进行了一次通用转换,工作正常,但是我在将Int64转换为Int32时遇到了一个问题

object var1 = (long)64;
int? var2 = Select<int?>(var1); // ERROR Int32Converter from Int64

public T Select<T>(object value)
{
  return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
}
objectvar1=(long)64;
智力?var2=选择(var1);//Int64中的Int32Converter错误
公共T选择(对象值)
{
return(T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
}

如何修复它?

如果没有显式转换,您无法将较大的类型转换为较窄的类型。

您不能改用
convert.ChangeType

int value = Convert.ChangeType(var1, TypeCode.Int32);


请注意,如果
var
超出了
Int32

的允许范围,这些将引发异常问题。问题是ChangeType与可空值类型(例如int?)不兼容

如果您测试可为null,然后转换为不可为null的类型,那么它应该可以工作。例如

object var1 = (long)64;
int? var2 = Select<int?>(var1); 

public T Select<T>(object value)
{
    var type = typeof(T);
    if (type.InheritsOrImplements(typeof(Nullable<>)))
        type = type.GetGenericArguments().First();
    // Non-nullable type can be cast as Nullable equivalent
    return (T)TypeDescriptor.GetConverter(type).ConvertFrom(value);
}

您得到的错误到底是什么?无法从System.Int64转换Int32Converter。为什么object var1=(long)64;int test=转换为32(var1);有效吗?因为当使用该功能时,在幕后某个时候会有一个明确的演员阵容。如果该值太大,Int32无法存储,则会引发异常。如果可能,我希望保持泛型。Convert.ChangeType(var1,typeof(T))抛出一个InvalidCastException…如果不使用
typeof(T)
,则为ChangeType指定TypeCode或一个显式函数,该函数在幕后使用
Int64
IConvertible
实现,这就是你想要的。看起来你对铸造和转化之间的区别感到困惑。有一个阅读帮助。类型转换器(尽管名称不同)并不真正支持使用
IConvertible
。。。
object var1 = (long)64;
int? var2 = Select<int?>(var1); 

public T Select<T>(object value)
{
    var type = typeof(T);
    if (type.InheritsOrImplements(typeof(Nullable<>)))
        type = type.GetGenericArguments().First();
    // Non-nullable type can be cast as Nullable equivalent
    return (T)TypeDescriptor.GetConverter(type).ConvertFrom(value);
}
public static bool InheritsOrImplements(this Type child, Type parent)
{
    if (child == null || parent == null) return false;

    parent = resolveGenericTypeDefinition(parent);
    if (parent.IsAssignableFrom(child)) return true;

    var currentChild = child.IsGenericType ? child.GetGenericTypeDefinition() : child;
    while (currentChild != typeof(object))
{
        if (parent == currentChild || hasAnyInterfaces(parent, currentChild)) return true;
        currentChild = currentChild.BaseType != null && currentChild.BaseType.IsGenericType
            ? currentChild.BaseType.GetGenericTypeDefinition() 
            : currentChild.BaseType;

        if (currentChild == null) return false;
    }
return false;
}