我的意思是,我想转换它:
string a = 24;
Convert.ChangeType(a, typeof(decimal?))
但它给我一个错误。
更新1:
我有一个Type对象,其中可以是decimal?,int?,..许多可以为null的类型。然后使用Type对象,我需要在对象类型中转换字符串值。
答案 0 :(得分:20)
看到一个很好的答案here:
public static T GetValue<T>(string value)
{
Type t = typeof(T);
t = Nullable.GetUnderlyingType(t) ?? t;
return (value == null || DBNull.Value.Equals(value)) ?
default(T) : (T)Convert.ChangeType(value, t);
}
E.g:
string a = 24;
decimal? d = GetValue<decimal?>(a);
答案 1 :(得分:5)
这是基于Dror的答案,但在处理空值时开销略小:
public static T GetValue<T>(string value)
{
if(value == null || DBNull.Value.Equals(value))
return default(T);
var t = typeof(T);
return (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(t) ?? t);
}
答案 2 :(得分:2)
由于Nullable<T>
未实施IConvertable
。
你可以这样做。
string a = 24;
decimal? aAsDecimal = (decimal)Convert.ChangeType(a, typeof(decimal));
我可能也会对TryParse
感兴趣吗?