简体   繁体   中英

dotnet, use dynamic object to initiate generic type

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()

Wrap the object into array:

myType.GetMethod("GetMatchingRules").Invoke(instance, new[]{ obj });

MethodBase.Invoke requires an array of parameters and will try to treat obj as one. The issue will become clear if you try casting the dynamic instance to ExpandoObject ( myType.GetMethod("GetMatchingRules).Invoke(instance, (ExpandoObject) obj); )

PS

Note that using dynamic is rarely a right choice in C# applications.

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