繁体   English   中英

当conversionType为可为null的int时如何使用Convert.ChangeType()

[英]How to use Convert.ChangeType() when conversionType is a nullable int

我的意思是,我想将其转换为:

string a = 24;
Convert.ChangeType(a, typeof(decimal?))

但这给我带来了一个错误。

更新1:

我有一个Type对象,其中可以是十进制?,int?,..许多可为空的类型。 然后,使用Type对象,我需要在type对象中转换字符串值。

在这里看到一个很好的答案:

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

这是基于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);
} 

由于Nullable<T>不实现IConvertable您无法执行此操作。

您可以执行此操作。

string a = 24;
decimal? aAsDecimal = (decimal)Convert.ChangeType(a, typeof(decimal));

我也可能对TryParse感兴趣吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM