c# - Convert.ChangeType 为可为空的 int 引发无效的强制转换异常

标签 c#

如果我调用下面的 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.ValueObject 类型而且你在这里动态转换,你不能直接转换 intint?通过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/

相关文章:

c# - 如何在 C# 中混合两个视频流?

c# - 如何调用具有多个参数的测试方法(NUnit)

c# - 具有非主键值的 FindAsync

c# - Linq 查询从嵌套对象获取值

c# - 设置饼图切片和图例的颜色

c# - 从代码隐藏添加文本到网页

c# - 有没有办法使用 C# 将 PST 文件导入 Outlook?

c# - 获取 AssemblyTitle

c# - Topshelf:成功安装服务后安装命令没有返回

c# - 我的 sql 数据库表中没有任何内容?