jeudi 8 juillet 2021

Activator.CreateInstance with Delegate parameter

I want to create an instance of the following type with reflection

    internal sealed class SomeClass
    {
        public delegate object SomeDelegate(object value);

        public SomeDelegateHandler { get; private set; }

        public SomeClass(SomeDelegate handler)
        {
            this.Handler = handler;
        }
    }

Usually I would use reflection to create instances of an internal class but since I need to pass a delegate I don't know how to do this.

How I I call a contructor that takes a delegate via reflection.

This is what I tried so far.


public static object SomeDelegateImplementation(object value)
{
    return value;
}

public void Main()
{
    // without reflection (this is how SomeClass is constructed without reflection inside ThirdParty assembly);
    var instance = new SomeClass(SomeDelegateImplementation);

    // with reflection 
    var assembly = typeof(ThirdParty.OtherClass).Assembly;
    var type = assembly.GetType("ThirdParty.SomeClass", true, true);
    var ctor = type.GetConstructors()[0];

    // compiler error: cannot convert method group 'SomeDelegateImplementation' to non-delegate type 'object'. Did you intend to invoke the method?
    var args = new object[]{ SomeDelegateImplementation }; 

    // throws a runtime error during invoke: 
    // error converting object with type "System.Func`2[System.Object,System.Object]" to type "ThirdParty.SomeClass+SomeDelegate".
    Func<object, object> someDelegateImplementation = SomeDelegateImplementation;
    var args = new object[]{ (Delegate)someDelegateImplementation }; 
    ctor.Invoke(args);
}





Aucun commentaire:

Enregistrer un commentaire