简体   繁体   中英

Generic type struct in dictionary

I want to create a C# struct that stores a class type property which later can be instantiated.

I created the struct like this:

internal struct Command<T>
{
    internal string trigger;
    internal T clazz;
    internal string category;
}

Then I want to store these Command structs in a dictionary:

private Dictionary<string, Command> _commandMap;

How do I define the dict so that its value type is set correctly for Command? Or is my whole approach wrong?

If you want your dictionary to be type specific:

private Dictionary<string, Command<my_type>> _commandMap;

If you want everything in one dictionary, then don't use a generic for the class.
You wrote, that you want to store a class type property to instantiate it later. Yet in your code you store a class instance, not a class type.
I think this is what you are looking for:

internal struct Command
{
    internal string trigger;
    internal Type clazz;
    internal string category;
}

or

internal struct Command
{
    internal string trigger;
    internal IMyInterface clazz;
    internal string category;
}

and finally:

private Dictionary<string, Command> _commandMap;

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