如何基于运行时类型创建泛型Dictionary并调用泛型方法?
基于运行时类型创建Dictionary并调用泛型方法的实现方案
一、创建运行时类型的Dictionary
要实现用运行时Type对象创建Dictionary<type, string>,需借助反射构造泛型类型:
// type为你通过反射获取到的运行时Type对象 Type dictType = typeof(Dictionary<,>).MakeGenericType(type, typeof(string)); IEnumerable dict = (IEnumerable)Activator.CreateInstance(dictType);
逻辑说明:
- 先获取
Dictionary<,>的开放泛型类型(未指定具体类型参数的版本) - 通过
MakeGenericType传入运行时type和string,生成具体泛型类型 - 用
Activator.CreateInstance创建实例,最后转为IEnumerable
二、调用接收泛型Dictionary的方法
分两种场景处理:
场景1:调用接收Type参数的方法(SomeMethod(Type))
直接传入构造好的dictType即可:
var result = SomeMethod(dictType);
场景2:调用泛型方法(SomeMethod<T>())
泛型方法的类型参数需编译时确定,因此要通过反射调用:
// 获取泛型方法定义(需指定参数列表避免重载冲突) MethodInfo method = typeof(YourClass).GetMethod("SomeMethod", Type.EmptyTypes); // 构造具体泛型方法 MethodInfo genericMethod = method.MakeGenericMethod(dictType); // 调用方法:null对应静态方法,实例方法需传入实例对象 var result = genericMethod.Invoke(null, null);
三、HttpClient反序列化的解决方案
针对你补充的反序列化需求,有两种实现方式:
方式1:反射调用泛型GetAsync<T>
// 构造目标泛型类型:Dictionary<type, string> Type dictType = typeof(Dictionary<,>).MakeGenericType(type, typeof(string)); // 获取GetAsync<T>方法定义 MethodInfo getAsyncMethod = typeof(HttpClient).GetMethods() .First(m => m.Name == "GetAsync" && m.IsGenericMethodDefinition && m.GetParameters().Length == 1); // 构造具体泛型方法并调用 MethodInfo genericGetAsync = getAsyncMethod.MakeGenericMethod(dictType); var task = (Task)genericGetAsync.Invoke(httpClient, new object[] { $"SomePath/{type.Name}" }); await task; // 提取反序列化结果 var result = task.GetType().GetProperty("Result").GetValue(task);
方式2:使用非泛型反序列化(更简洁)
直接用System.Text.Json的非泛型反序列化方法,避免反射调用泛型方法:
HttpResponseMessage response = await httpClient.GetAsync($"SomePath/{type.Name}"); string json = await response.Content.ReadAsStringAsync(); Type dictType = typeof(Dictionary<,>).MakeGenericType(type, typeof(string)); var result = JsonSerializer.Deserialize(json, dictType);
内容的提问来源于stack exchange,提问作者Zenith
相关产品推荐
相关产品推荐

