簡體   English   中英

Activator.CreateInstance 與 Delegate 參數

[英]Activator.CreateInstance with Delegate parameter

我想用反射從第三方程序集創建一個內部類的實例。

這門課看起來像這樣

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

        public SomeDelegateHandler { get; private set; }

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

通常我會使用反射來創建內部類的實例,但我需要傳遞一個SomeDelegate委托。

由於該委托位於內部類中,因此我也需要通過反射創建該委托的實例。 但我已經嘗試過的一切都沒有奏效

這是我到目前為止所嘗試的。

// This is the method that I need to pass as an argument
public static object SomeDelegateImplementation(object value)
{
    return value;
}

public void Main()
{
    // example: create SomeClass without reflection 
    // (this is how SomeClass is usually constructed);
    var instance = new SomeClass(SomeDelegateImplementation);

    // setup: get the ConstructorInfo so I can use 
    // ctor.Invoke(...) to create an instance of that class
    var assembly = typeof(ThirdParty.OtherClass).Assembly;
    var type = assembly.GetType("ThirdParty.SomeClass", true, true);
    var ctor = type.GetConstructors()[0];

    // method one (doesn't work)
    // compiler error: cannot convert method group 'SomeDelegateImplementation' to non-delegate type 'object'. Did you intend to invoke the method?
    var args = new object[]{ SomeDelegateImplementation }; 
    var instance = ctor.Invoke(args);

    // method two (doen't work)
    // 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 }; 
    var instance = ctor.Invoke(args);
}

解決方案

感謝@JonSkeet,我設法使用Delegate.CreateDelegate創建了SomeClass的實例

    Assembly assembly = typeof(ThirdParty.OtherClass).Assembly;
    Type type = assembly.GetType("ThirdParty.SomeClass", true, true);
    ConstructorInfo ctor = type.GetConstructors()[0];

    // get a reference to the original delegate type
    Type someDelegateHandler Type =
        assembly.GetType("ThirdParty.SomeClass+SomeDelegateHandler", true, true);

    // get a reference to my method
    MethodInfo someDelegateImplementationMethod = 
        typeof(Program).GetMethod("SomeDelegateImplementation", 
            BindingFlags.Static | BindingFlags.NonPublic);

    // create a delegate that points to my method
    Delegate someDelegateImplementationDelegate = 
        Delegate.CreateDelegate(
            someDelegateHandler, someDelegateImplementationMethod);

    object[] args = new object[]{ someDelegateImplementationDelegate  };
    object instance = ctor.Invoke(args);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM