如何在Type变量中创建具有任何类型的Dictionary? [英] How to create a Dictionary with any types in Type variables?

查看:127
本文介绍了如何在Type变量中创建具有任何类型的Dictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我正面临这个问题,我需要创建一个包含任何类型案例的Dictionary实例。类型由方法的参数传递。
我不只是想创建一个动态或对象类型的Dictionary,因为使用我的库会给用户带来很多转换问题。
我也不能使用简单的构造函数,因为我的方法用数据(存储在文件中)实际填充字典。通过Type变量创建特定的词典很重要。
这就是我的想法:

Currently im facing the problem I need to create an instance of Dictionary with any type of its cases. The types are delivered by the arguments of the method. I do not simply want to create a dynamic or object type Dictionary, because this faces the user alot of convertion problems by using my library. I also cannot use a simple constructor, because my method fills the Dictionary with data (that is stored in a file) in real. It's important to create the specific dictionary by Type variables. This is what im thinking of:

public static Dictionary<dynamic, dynamic> createDict(Type type1, Type type2)
{
    // how to create the dictionary?
    // im filling my dictionary with any data ...
    return dict;
}

用户在这里调用我的方法:

Here the user calls my method:

Dictionary<string, int> dict = MyLib.createDict(typeof(string), typeof(int));
// or
MyOwnType myInstance = new MyOwnType();
Dictionary<string, MyOwnType> dict = MyLib.createDict(typeof(string), myInstance.GetType());


推荐答案

Type dictType = typeof(Dictionary<, >).MakeGenericType(Type1, Type2);
var dict = Activator.CreateInstance(dictType);




  • 获取词典的类型

  • 使用 MakeGenericType

  • 创建具有指定类型的通用类型使用 Activator.CreateInstance

    • Get the Type for Dictionary
    • Create a generic type with the specified Types using MakeGenericType
    • Create an instance of the generic type using Activator.CreateInstance
    • 这篇关于如何在Type变量中创建具有任何类型的Dictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆