我有下面的代碼和我需要一個字符串轉換爲一個類型,也是從字符串指定:如何將字符串轉換爲運行時確定的可空類型?
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
object d = Convert.ChangeType("2012-02-23 10:00:00", t);
我得到了以下錯誤消息:
Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
如何將這項很可能嗎?
我知道一個醜陋的方式是檢查的類型是否爲空,如果使用:
Type possiblyNullableType = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
var underlyingType = Nullable.GetUnderlyingType(possiblyNullableType);
Object result;
// if it's null, it means it wasn't nullable
if (underlyingType != null)
{
result = Convert.ChangeType("2012-02-23 10:00:00", underlyingType);
}
會不會有什麼更好的辦法?
謝謝,
爲什麼你需要檢查t.IsGenericType? t.GetGenericTypeDefinition()== typeof(Nullable <>)部分將覆蓋該部分;不是嗎? – 2012-02-24 12:09:30
@William'GetGenericTypeDefinition()'如果類型不是泛型的,則拋出異常。 – hvd 2012-02-24 13:41:42