动态转换可空类型

时间:2016-12-12 20:22:59

标签: c# dynamic types type-conversion nullable

我尝试使用以下代码行根据方法的参数对象类型动态转换对象:

Convert.ChangeType(parameter.Value, parameterType);

但是,当parameterType相当于DateTime?int?或任何其他可以为空的类型时,此转换不起作用。

为什么这种转换不适用于可空类型,有没有办法让它可以使用可空类型?

(注意:这一切都是动态完成的,所以没有办法事先知道类型是否可以为空...除非Type类有解释的方法,我可以然后实现某种类型的if (nullable object) { // do special conversion }?)

编辑:

看看这个问题:How to use Convert.ChangeType() when conversionType is a nullable int

我已尝试实施以下答案:

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

然而,通过执行以下操作来使用此答案:

string a = 24;
decimal? d = GetValue<decimal?>(a);

但在我的情况下,我不一定知道它会是decimal?类型;我需要传递我要转换它的Type,例如我需要做类似的事情:

Type parameterType = parameterDescriptor.ParameterType;
var unknownType = GetValue<parameterType>(parameter.Value);

0 个答案:

没有答案