控制器类中确定对象类型并实现泛型反序列化与泛型方法调用
实现方案
泛型参数必须在编译期确定,你需要通过反射动态构造泛型类型、调用泛型方法来适配运行时才知道的类型,具体实现如下:
- 先获取目标类型的
Type实例
// 注意要填写类型的完整限定名(包含命名空间),如果类型在当前执行程序集外还需要指定程序集信息 string typeFullName = $"你的业务命名空间.{objectType}"; // 替换成实际的类所属命名空间 Type? entityType = Type.GetType(typeFullName); if (entityType == null) { // 自定义处理类型不存在的异常逻辑 throw new ArgumentException($"非法类型名:{objectType}"); }
- 构造
IEnumerable<T>泛型类型并反序列化
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(entityType); // 直接调用System.Text.Json的非泛型反序列化重载 object? list = System.Text.Json.JsonSerializer.Deserialize(content.ToString(), enumerableType); if (list == null) { // 自定义处理反序列化失败逻辑 }
- 反射调用泛型
InsertObject方法
// 替换YourServiceType为你services变量的实际类型 var insertMethod = typeof(YourServiceType) .GetMethod(nameof(YourServiceType.InsertObject)) ?.MakeGenericMethod(entityType); if (insertMethod == null) { // 自定义处理方法不存在的异常逻辑 throw new MissingMethodException("未找到匹配的InsertObject方法"); } // 执行方法获取返回值 var output = insertMethod.Invoke(services, new object[] { list });
优化建议
- 如果这段逻辑调用频率很高,可以提前缓存构造好的
entityType和泛型方法实例,避免每次反射带来的性能损耗 - 可以新增合法类型校验逻辑,限制仅允许传入
Dog/Cat等预设的类型值,避免传入非法类型名触发异常
内容的提问来源于stack exchange,提问作者netcoredev
相关产品推荐
相关产品推荐

