简体   繁体   中英

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.

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:

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.

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.

Only as a last resort would I look to reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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