如何使用反射向现有的委托添加另一个(对象)委托?

问题描述 投票:0回答:1

我不知道如何强制转换 d 以使用 += 运算符将下一个方法添加到 d。

这是最简单的方法吗? 正如所解释的,第一个委托位于类之外,并且必须通过反射(而不是表达式、表达式树、发出等)进行更改。

using System;
using System.Reflection;

public class A
{
    public void fn()
    {
        Console.WriteLine ("a.fn() \n");
    }
    public void fn1()
    {
        Console.WriteLine ("a.fn1()");
    }
    void start()
    {
         var cb = new B();
         FieldInfo fi  = cb.GetType().GetField("mD");
         MethodInfo mfn  = this.GetType().GetMethod("fn");
         
         object d = System.Delegate.CreateDelegate( fi.FieldType, this, mfn);
//              d += System.Delegate.CreateDelegate( fi.FieldType, this, mfn1); 
// Line above give me an error CS0019: Operator '+=' cannot be applied to operands of type 'object' and 'Delegate'
// I think it due d is object not MD()


        fi.SetValue(cb, d);
        cb.tst();
    }
    
    public static void Main(string[] args)
    {
        var ca = new A();
        ca.start();
    }
}
public class B
{
    public delegate void    MD();
    public          MD mD ;
    public B()
    {
        mD = fn;
        tst();
    }
    public void tst()
    {
        mD();
    }
    void fn()
    {
         Console.WriteLine ("b.fn() \n");
    }
}

我不知道如何以最简单的方式解决它。 当然我读过一些文章但还是没有。

现在,如果我不使用 += 并生成下一个输出,代码可以正常工作:

b.fn()

a.fn()

c# reflection delegates
1个回答
0
投票

您需要将委托对象转换为目标类型 -

B.MD
,然后它应该可以工作:

var d = (B.MD) System.Delegate.CreateDelegate(fi.FieldType, this, mfn);
d += fn1;
© www.soinside.com 2019 - 2024. All rights reserved.