2011-02-16 82 views
2

我有一個通用的方法在MySQL連接器女巫進行通用轉換。 我簡化它的問題,因爲它使很多事情。 最後,它進行了一個通用的轉換並正常工作,但我有一個問題將Int64轉換爲Int32。與Int64的通用轉換

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

我該如何解決?

+0

一個方便的擴展方法到底是什麼,你得到的錯誤? – thecoop 2011-02-16 13:39:10

+0

無法從System.Int64中轉換Int32Converter。 – 2011-02-16 13:41:52

回答

3

如果沒有顯式轉換,則無法從較大類型轉換爲較窄類型。

+0

爲什麼對象var1 =(long)64; int test = Convert.ToInt32(var1);作品? – 2011-02-16 13:47:30

3

你不能用Convert.ChangeType代替嗎?

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

int value = Convert.ToInt32(var1); 

注意,這些會拋出異常,如果varInt32

2

的問題超出了允許範圍是一changeType不與空值類型兼容(例如,詮釋?)。

如果你測試可空的<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是類型

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