根据运行时值获取泛型类型的字典

Zen*_*ith 3 .net c# reflection types

我希望声明一个基于运行时类型的字典。因此,不要这样做:

IEnumerable dict = null;
if(type == typeof(SomeType)) dict = new Dictionary<SomeType, string>()
if(type == typeof(SomeOtherType)) dict = new Dictionary<SomeOtherType, string>()
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情:

IEnumerable dict = new Dictionary<type, string>();
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这个目标?另外,我希望能够通过以下方式之一调用仅使用字典类型的不同方法:

var result = SomeMethod(typeof(Dictionary<type, string>));
Run Code Online (Sandbox Code Playgroud)
var result = SomeMethod<Dictionary<type, string>>();
Run Code Online (Sandbox Code Playgroud)

编辑:额外的上下文:

我从不同的 API 调用中获取类型作为字符串。然后,我使用反射通过 AssemblyQualifiedName 获取类型,这会生成一个用于执行调用的列表。根据这些类型的名称,需要调用 REST 端点。

If (type == SomeType) httpClient.GetAsync("SomePath/{SomeType.Name}")
Run Code Online (Sandbox Code Playgroud)

此端点返回一个 Dictionary<SomeType, string>。为了能够反序列化这些类型,我需要调用类似的东西

httpClient.GetAsync<Dictionary<type, string>>("SomePath/{SomeType.Name}")
Run Code Online (Sandbox Code Playgroud)

否则System.Text.Json包中会出现异常。

Jon*_*eet 6

如果您真的不关心编译时的类型,而只想创建一个实例,则可以通过反射轻松地做到这一点:

var dictionaryType = typeof(Dictionary<,>).MakeGenericType(type, typeof(string));
var dictionary = Activator.CreateInstance(dictionaryType);
Run Code Online (Sandbox Code Playgroud)

上面的结构dictionaryType还可以让你调用:

var result = SomeMethod(dictionaryType);
Run Code Online (Sandbox Code Playgroud)

  • @StijnWingens:不,请用*所有*相关上下文提出一个新问题。(我不知道你的意思是什么,即使它“很”清楚,在评论中提出后续问题也是不合适的。) (2认同)