的問題超出了允許範圍是一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;
}
一個方便的擴展方法到底是什麼,你得到的錯誤? – thecoop 2011-02-16 13:39:10
無法從System.Int64中轉換Int32Converter。 – 2011-02-16 13:41:52