我希望声明一个基于运行时类型的字典.因此,与其这样做,不如:
IEnumerable dict = null;
if(type == typeof(SomeType)) dict = new Dictionary<SomeType, string>()
if(type == typeof(SomeOtherType)) dict = new Dictionary<SomeOtherType, string>()
我希望这样做:
IEnumerable dict = new Dictionary<type, string>();
我怎样才能做到这一点呢?此外,我还希望能够通过以下方式之一仅使用字典的类型调用不同的方法:
var result = SomeMethod(typeof(Dictionary<type, string>));
var result = SomeMethod<Dictionary<type, string>>();
编辑: 额外的上下文:
我从另一个API调用中以字符串形式获取类型.然后,我使用反射通过Assembly QualifiedName获取类型,这将产生一个执行调用的列表.根据这些类型的名称,需要调用REST端点.
If (type == SomeType) httpClient.GetAsync("SomePath/{SomeType.Name}")
此终结点返回字典<;SomeType,字符串>;.为了能够反序列化这些类型,我需要调用类似
httpClient.GetAsync<Dictionary<type, string>>("SomePath/{SomeType.Name}")
否则,System.Text.Json包中将出现异常.