[英]Generic conversion with Int64
我在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);
}
我該如何解決?
你不能使用Convert.ChangeType
嗎?
int value = Convert.ChangeType(var1, TypeCode.Int32);
要么
int value = Convert.ToInt32(var1);
請注意,如果var
超出Int32
的允許范圍,這些將拋出異常
沒有顯式強制轉換,您無法從較大的類型轉換為較窄的類型。
問題是ChangeType與可空值類型(例如int?)不兼容。
如果您測試Nullable <T>然后轉換為非可空類型,它應該工作。 例如。
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);
}
BTW ... InheritsOrImplements是Type的一個方便的擴展方法
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.