'Dynamic Type Conversion in C#
I have a lot of lists of different types, and a dictionary that stores for each type the according list. I would like to add an item to the list of its type:
class Demo
{
[Serializable] class A{}
[Serializable] class B{}
[Serializable] class Z{}
List<A> a = new List<A>();
List<B> b = new List<B>();
List<Z> z = new List<Z>();
Dictionary<Type, object> dict;
Demo()
{
dict = new Dictionary<Type, object>
{
{typeof(List<A>), a},
{typeof(List<B>), b},
{typeof(List<Z>), z},
};
}
void Add(dynamic items)
{
var type = items.GetType();
dynamic list = dict[type];
list.AddRange( items );
}
static void Main()
{
var demo = new Demo();
var json = JsonConvert.SerializeObject(new List<B>(){new B()});
var type = typeof(List<B>);
//compiler has no information of the type of item
//the type used for deserialization is not known at compile time
var item = JsonConvert.DeserializeObject(json, type );
demo.Add(item);
}
}
This is working, but I wonder whether there is a solution without using the dynamic type -
Is there a way to convert the entry in the dictionary to List<T>, or do you have another idea how to solve this problem dynamically without dynamic?
Please note that I cannot use
void Add<T>( T item ) {...}
Since the compile-time-type of the item is object, for instance from
object item = JsonConvert.DeserializeObject( json , item_type );
Solution 1:[1]
use reflection:
void Add(object items)
{
var type = items.GetType();
var method = type.GetMethod("AddRange");
var list = dict[type];
var ret = method.Invoke(list, new object[]{items} );
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | draz |
