![](/img/trans.png)
[英]How to use Convert.ChangeType() when conversionType is a nullable int
[英]Convert.ChangeType throwing Invalid Cast Exception for nullable int
如果我在下面调用GetClaimValue方法(其中T是可为null的int),则获取无效的Cast异常。
private static T GetClaimValue<T>(string claimType, IEnumerable<Claim> claims)
{
var claim = claims.SingleOrDefault(c => c.Type == claimType);
if (claim != null)
return (T) Convert.ChangeType(claim.Value, typeof(T));
return default(T);
}
例如:
GetClaimValue<int?>(IdentityServer.CustomClaimTypes.SupplierId, claims)
有人知道如何处理吗?
我假设Claim.Value
是Object
类型,并且您在此处进行动态转换,您无法直接将int
转换为int?
通过Convert.ChangeType
。
一种选择是使用Nullable.GetUnderlyingType
,它将检查这是否为可为空的结构情况,首先通过基础数据类型进行转换,然后转换为T
您还需要处理null
方案。
if (claim != null)
{
var conversionType = typeof(T);
if (Nullable.GetUnderlyingType(conversionType) != null)
{
if (claim.Value == null) //check the null case!
return default(T);
//use conversion to `int` instead if `int?`
conversionType = Nullable.GetUnderlyingType(conversionType);
}
return (T)Convert.ChangeType(claim.Value, conversionType);
}
我无法解释为什么它会引发异常,但是当我使用Convert.ChangeType
时,我遇到了类似的情况。
尝试先获取您传入的类型的转换器,然后使用该转换器进行转换。 使用此方法可获得更好的结果。
var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)converter.ConvertFrom(claim.Value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.