Is it possible to add a dictionary
to another dictionary
that contains different dictionary values?
Dictionary<String, Func<String>> d1 = new Dictionary<String,Func<String>>();
Dictionary<String, Func<String,String>> d2 = new Dictionary<String, Func<String,String>>();
Dictionary<String, Dictionary> dHolder = new Dictionary<String, Dictionary>();
dHolder.add("key",d1);
dHolder.add("key",d2);
You can do this if you use the IDictionary
interface, which all dictionaries (no matter what type parameters they use) inherit from.
Dictionary<String, Func<String>> d1 = new Dictionary<String,Func<String>>();
Dictionary<String, Func<String,String>> d2 = new Dictionary<String, Func<String,String>>();
Dictionary<String, IDictionary> dHolder = new Dictionary<String, IDictionary>();
dHolder.Add("key1", d1);
dHolder.Add("key2", d2);
However, you'll need to go through the pain of unboxing the values when you retrieve them.
You can, but not quite the way you have written.
var dict1 = new Dictionary<string, ObjectTypeA>();
var dict2 = new Dictionary<string, ObjectTypeB>();
var holder = new Dictionary<string, IDictionary>();
holder["key1"] = dict1;
holder["key2"] = dict2;
The only issue you have is now you've lost your generic types, so you need to check what type of dictionary you have when you take the key out.
var val = holder["key1"]; //Returns an IDictionary
var dictType1 = holder["key1"] as Dictionary<string, ObjectTypeA>;
//dictType1 will be null if it isn't a Dictionary<string, ObjectTypeA>
So you will have to do some type checking/conversion at some point, but you can still interact with it as an IDictionary if you don't need strong typing.
holder["key1"]["newKey"] = new ObjectTypeA(); //Works
holder["key1"]["newKey2"] = new ObjectTypeB(); //Runtime exception
One way would be making TValue of dHolder
an Object
and then cast it to relevant type after retrieval.
Dictionary<String, Func<String>> d1 = new Dictionary<String, Func<String>>();
Dictionary<String, Func<String, String>> d2 = new Dictionary<String, Func<String, String>>();
Dictionary<String, Object> dHolder = new Dictionary<String, Object>();
dHolder.Add("key1", d1);
dHolder.Add("key2", d2);
Dictionary<String, Func<String>> val1 = dHolder["key1"] as Dictionary<String, Func<String>>;
Dictionary<String, Func<String, String>> val2 = dHolder["key2"] as Dictionary<String, Func<String, String>>;
Remarks:
as
operator returns null
if cast fails. TryGetValue
method of the dictionary to safely retrieve value by its key.
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.