简体   繁体   English

使用函数传递的自定义类型创建字典C#

[英]Creating Dictionary C# with custom type passed by function

I want to create a Dictionary with TKey as string and the TValue to be from type which is not know at compile time. 我想创建一个字典,其中TKey为字符串,TValue来自于编译时不知道的类型。

Let's say for example I have a function 假设我有一个功能

 createDict(Type type)
 {
     Dictionary<string, {here's the type from the func. argument}> dict = new Dictionary..

 }

Is this scenario possible or I'm missing something very basic ? 这是可能的情况还是我缺少一些非常基本的东西?

It can be done if you pass type as a parameter: 如果将type作为参数传递,则可以完成此操作:

var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string),type);
var dictionary = (IDictionary)Activator.CreateInstance(dictionaryType);

usage of such dictionary will be harder due to you take full responsibility on correctness of what is inserted to this dictionary. 由于您对本词典中所插入内容的正确性承担全部责任,因此使用此类词典将更加困难。

Make the method generic: 使方法通用:

public void CreateDict<T>()
{
    Dictionary<string,T> dict = new Dictionary<string,T>();

}

Though you may want the return type to also be Dictionary<string,T> and add constrains to the generic type parameter. 尽管您可能希望返回类型也为Dictionary<string,T>并将约束添加到泛型类型参数。

You would call it as: 您将其称为:

CreateDict<MyCustomType>();

The above assumes the type can be passed in during compile time. 上面假设类型可以在编译时传入。

You can do with a bit of reflection: 您可以进行一些反思:

Type dict = typeof (Dictionary<,>);
Type[] parameters = {typeof (string), type};
Type parametrizedDict = dict.MakeGenericType(parameters);
object result = Activator.CreateInstance(parametrizedDict);

所有实例和类都是对象,所以为什么不使用Dictionary<string,object>并且使用与MVC,Session或Cache中的ViewData相同的方式进行转换,它们都需要转换。

Use generics if type is known at compile time: 如果在编译时知道类型,则使用泛型:

void Main()
{
    var dict = CreateDict<int>();
    dict["key"] = 10;
}

Dictionary<string, T> CreateDict<T>()
{
    return new Dictionary<string, T>();
}

If not, refactor to use a base type or interface eg: 如果不是,请重构为使用基本类型或接口,例如:

var dic = new Dictionary<string, IMyType>();

where IMyType exposes the common traits of the type that you wish to keep in the dictionary. IMyType公开了您希望保留在字典中的类型的常见特征。

Only as a last resort would I look to reflection. 我只有在万不得已的情况下才会反思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM