[英]How to Convert a String to a Nullable Type Which is Determined at Runtime?
我有下面的代碼,我需要將一個字符串轉換為一個也從String指定的類型:
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]]'.
怎么會很好的可能?
我知道一種丑陋的方法是使用if來檢查類型是否可以為空:
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);
}
會有更好的方法嗎?
謝謝,
有兩個問題。
首先, Convert.ChangeType
just plain不支持可空類型。
其次,即使它確實如此,通過裝箱結果(將其分配給object
),您已經將其轉換為DateTime
。
您可以使用特殊情況可為空的類型:
string s = "2012-02-23 10:00:00";
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
object d;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (String.IsNullOrEmpty(s))
d = null;
else
d = Convert.ChangeType(s, t.GetGenericArguments()[0]);
}
else
{
d = Convert.ChangeType(s, t);
}
我編寫了以下通用助手方法,該方法適用於大多數場景(未使用泛型類型進行測試):
static void Main(string[] args)
{
Object result =
ConvertValue(
"System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]",
"2012-02-23 10:00:00");
}
public static Object ConvertValue(string typeInString, string value)
{
Type originalType = Type.GetType(typeInString);
var underlyingType = Nullable.GetUnderlyingType(originalType);
// if underlyingType has null value, it means the original type wasn't nullable
object instance = Convert.ChangeType(value, underlyingType ?? originalType);
return instance;
}
public static T GetValue<T>(string Literal, T DefaultValue)
{
if (Literal == null || Literal == "" || Literal == string.Empty) return DefaultValue;
IConvertible obj = Literal;
Type t = typeof(T);
Type u = Nullable.GetUnderlyingType(t);
if (u != null)
{
return (obj == null) ? DefaultValue : (T)Convert.ChangeType(obj, u);
}
else
{
return (T)Convert.ChangeType(obj, t);
}
}
像這樣的東西? 除非你真的需要動態地做。
if (string.IsNullOrEmpty(input))
{
return new DateTime?();
}
else
{
return new DateTime?(DateTime.Parse(input));
}
可能你可以查看你的類型是否是'可空'類型之一,然后你可以找到一些有用的東西:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.