代码之家  ›  专栏  ›  技术社区  ›  wingyip

Convert.ChangeType引发可为null的int的无效强制转换异常

c#
  •  2
  • wingyip  · 技术社区  · 7 年前

    如果我调用下面的GetClaimValue方法,其中T是可为null的int,则会得到一个无效的强制转换异常。

    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)
    

    有人知道怎么处理吗?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Chris Sinclair    7 年前

    我猜 Claim.Value 属于类型 Object int int? 通过 Convert.ChangeType

    一种选择是使用 Nullable.GetUnderlyingType 它将检查这是否是一个可为null的结构,首先通过基础数据类型进行转换,然后转换为 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);
    }
    
        2
  •  2
  •   Brandon    7 年前

    我无法解释为什么它会抛出异常,但是当我使用 Convert.ChangeType .

    试着抓住你首先传入的类型的转换器,然后用它来转换。我用这种方法得到了更好的结果。

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