I need to create an Instance of a generic class using dynamic object
Using the following code sample
using System;
using System.Dynamic;
public class Program
{
public static void Main()
{
dynamic obj = new ExpandoObject();
obj.num = 1;
obj.str = "a";
Type t = obj.GetType();
Type myType = typeof(RulesService<>).MakeGenericType(t);
object instance = Activator.CreateInstance(myType, 999);
myType.GetMethod("GetMatchingRules")
.Invoke(instance, obj);
}
}
public class RulesService<T>
{
private readonly int _retNum = 0;
public RulesService(int retNum)
{
_retNum = retNum;
}
public int GetMatchingRules(T objectToMatch)
{
Console.WriteLine("GetMatchingRules");
return _retNum;
}
}
and getting the next exception
Unhandled exception. Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Reflection.MethodBase.Invoke(object, object[])' has some invalid arguments at CallSite.Target(Closure , CallSite , MethodInfo , Object , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2) at Program.Main()
Aucun commentaire:
Enregistrer un commentaire