You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Session Storage:如何传递未知类型

解决Blazor中SessionStorage统一获取对象的类型错误问题

你代码里的GetAsync<obj>报错,是因为obj是方法参数(变量),但泛型参数需要传入类型,不能用变量代替。以下两种方式可以实现你的需求:

方案1:使用泛型方法(推荐)

这种方式无需反射,代码简洁且类型安全,直接通过泛型参数指定目标类型:

public async Task<T?> GetFromStorageAsync<T>(string key)
{
    try
    {
        var result = await PSession.GetAsync<T>(key);
        return result.Success ? result.Value : default;
    }
    catch (Exception)
    {
        // 可按需添加日志等异常处理逻辑
        return default;
    }
}

使用示例:

// 获取User类型对象
var user = await GetFromStorageAsync<User>("user_key");
// 获取int类型数值
var count = await GetFromStorageAsync<int>("count_key");

方案2:使用反射实现(动态指定类型场景)

如果需要动态传入类型(而非编译时确定),可以通过反射调用泛型的GetAsync方法:

public async Task<object?> GetFromStorageAsync(string key, Type targetType)
{
    try
    {
        // 获取GetAsync泛型方法的定义
        var methodDef = typeof(PSession).GetMethod("GetAsync", new[] { typeof(string) });
        if (methodDef == null)
            return null;
        
        // 构造对应类型的泛型方法
        var genericMethod = methodDef.MakeGenericMethod(targetType);
        // 调用方法(若PSession是实例类,第一个参数传实例对象)
        var taskResult = await (Task)genericMethod.Invoke(null, new object[] { key });
        
        // 提取返回结果的Success和Value属性
        var successProp = taskResult.GetType().GetProperty("Success");
        var valueProp = taskResult.GetType().GetProperty("Value");
        if (successProp == null || valueProp == null)
            return null;
        
        bool isSuccess = (bool)successProp.GetValue(taskResult);
        return isSuccess ? valueProp.GetValue(taskResult) : null;
    }
    catch (Exception)
    {
        return null;
    }
}

使用示例:

// 获取User类型对象
var user = await GetFromStorageAsync("user_key", typeof(User));
// 获取int类型数值
var count = await GetFromStorageAsync("count_key", typeof(int));

注意事项

  • 方案1是首选,编译时即可检查类型正确性,性能远高于反射。
  • 方案2仅适用于无法提前确定类型的动态场景,反射会带来额外性能开销,且代码复杂度更高。

内容的提问来源于stack exchange,提问作者dbay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:36:18