简体   繁体   中英

Dictionary - using type as key and constraint it to only to certain types

Is it possible, if we use a Type as key for a dictionary, to constrain that type only to specific ones? For example:

public abstract class Base
{ }

public class InheritedObject1 : Base
{ }

public class InheritedObject2 : Base
{ }

public class Program
{
    public Dictionary<Type, string> myDictionary = new Dictionary<Type, string>();
}

So from the code given above for instance i want to constraint the Type only to : Base and every class which inherits from it. Is it possible to make such a constraint?

Just create a template class that inherits from Dictionary , as so:

class CustomDictionary<T> : Dictionary<T, string>
    where T : Base
{
}

Then you can use it in your code as required:

    public void Test()
    {
        CustomDictionary<InheritedObject1> Dict = new CustomDictionary<InheritedObject1>();

        Dict.Add(new InheritedObject1(), "value1");
        Dict.Add(new InheritedObject1(), "value2");
    }

Well if you do

public Dictionary<Base, string> myDictionary = new Dictionary<Base, string>();

then only Base and its children will be able to be used as the key (in this specific case Base is abstract so only children applies).

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