Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Type at Runtime with GenericTypeArgument

Tags:

c#

generics

This is what I am trying to get

(IList<Foo>)listPropertyInfo.GetValue(item)

This is how I get Foo type

listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]

This is what I tried but couldn't make it successfully

Convert.ChangeType(listPropertyInfo.GetValue(item), IList<listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]>)

and also this;

((typeof(IList<>).MakeGenericType(listPropertyInfo.GetValue(item).GetType().GenericTypeArguments.Single())))(listPropertyInfo.GetValue(item))

this is method where I am trying to implement

public static void trigger(IList<T> result)
{
    foreach (var item in result)
    {
        foreach (var listPropertyInfo in typeof(T).GetProperties().ToList().FindAll(x => x.PropertyType.Name == typeof(IList<>).Name))
        {
             trigger((IList<Foo>)listPropertyInfo.GetValue(item));
        }
    }
}
like image 364
Mert Avatar asked Jun 06 '15 15:06

Mert


1 Answers

I solved like this;

IList targetList = (IList)listPropertyInfo.GetValue(item);
Type foo = targetList.GetType().GenericTypeArguments.Single();
Type unboundGenericType = typeof(READ<>);
Type boundGenericType = unboundGenericType.MakeGenericType(foo);
MethodInfo doSomethingMethod = boundGenericType.GetMethod("trigger");
object instance = Activator.CreateInstance(boundGenericType);
doSomethingMethod.Invoke(instance, new object[] { targetList, f, properties });
like image 117
Mert Avatar answered Nov 06 '22 05:11

Mert