如果我调用下面的 GetClaimValue 方法,其中 T 是一个可为空的 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)
有谁知道如何处理这个问题?
最佳答案
我假设 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);
}
关于c# - Convert.ChangeType 为可为空的 int 引发无效的强制转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011924/