简体   繁体   English

Convert.ChangeType引发可空int的无效转换异常

[英]Convert.ChangeType throwing Invalid Cast Exception for nullable int

Getting an Invalid Cast Exception if I call the GetClaimValue method below where T is a 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);
}

For example: 例如:

 GetClaimValue<int?>(IdentityServer.CustomClaimTypes.SupplierId, claims)

Anyone know of a way to deal with this? 有人知道如何处理吗?

I'm assuming Claim.Value is of type Object and you're dynamically converting here, you can't straight up convert an int to an int? 我假设Claim.ValueObject类型,并且您在此处进行动态转换,您无法直接将int转换为int? via Convert.ChangeType . 通过Convert.ChangeType

One option is to use Nullable.GetUnderlyingType which will check if this is a nullable struct case, do the conversion via the underlying data type first, then cast to T . 一种选择是使用Nullable.GetUnderlyingType ,它将检查这是否为可为空的结构情况,首先通过基础数据类型进行转换,然后转换为T

You'll also need to handle the null scenario as well. 您还需要处理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);
}

I can't explain why it's throwing an exception, however I had a similar situation when I was using Convert.ChangeType . 我无法解释为什么它会引发异常,但是当我使用Convert.ChangeType时,我遇到了类似的情况。

Try grabbing the converter of the type you pass in first, then use that to convert. 尝试先获取您传入的类型的转换器,然后使用该转换器进行转换。 I've had better results using this method. 使用此方法可获得更好的结果。

var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)converter.ConvertFrom(claim.Value);

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

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