Delegate的Target,Method

在 C# 中,Delegate 是一种引用方法的类型,可以将方法视为对象进行传递和操作。Delegate 类型的实例可以用来引用一个或多个方法,然后可以将这些引用作为参数传递给其他方法,或者用来调用这些方法。

Delegate 类型包含两个属性:Target 和 Method。其中,Target 属性表示委托引用的对象,Method 属性表示委托引用的方法(MethodInfo),当调用多播委托时,它会依次调用每个方法。在这种情况下,Target 属性返回委托引用的最后一个方法的对象,如果是静态方法,则为null。

public class TestA
    {
        public void print()
        {
            Console.WriteLine("this is testA");
        }
        public virtual void printH()
        {
            Console.WriteLine("this is testH in A");
        }
    }

    public class TestB : TestA
    {
        public static void StaticMethod()
        {
            Console.WriteLine("this is static method of TestB");
        }
        public new void print()
        {
            Console.WriteLine("this is testB");
        }
        public override void printH()
        {
            Console.WriteLine("this is testH in B");
        }
    }

    class ProgramA
    {
        static void Main()
        {

            Action actA = null,actB=null,actC=null;
            var a = new TestA();
            var b = new TestB();
            actA += a.print;
            actA += a.printH;
            Console.WriteLine(actA.Target==a);
            Console.WriteLine(actA.Method==typeof(TestA).GetMethod("printH"));
            actB += b.print;
            actB += b.printH;
            actB += TestB.StaticMethod;
            Console.WriteLine(actB.Target==null);
            Console.WriteLine(actB.Method==typeof(TestB).GetMethod("StaticMethod"));
            actC = actA + actB;
            var c = actC.GetInvocationList();
            Console.WriteLine("c length:"+c.Length);
            foreach(Delegate d in c)
            {
                Console.WriteLine($"Target:{d.Target},MethodInfo:{d.Method}");
            }
            Console.ReadLine();
        }
    }

output:

True
True
True
True
c length:5
Target:EasyBimBackend.TestA,MethodInfo:Void print()
Target:EasyBimBackend.TestA,MethodInfo:Void printH()
Target:EasyBimBackend.TestB,MethodInfo:Void print()
Target:EasyBimBackend.TestB,MethodInfo:Void printH()
Target:,MethodInfo:Void StaticMethod()

posted @ 2023-03-11 17:30  JohnYang819  阅读(176)  评论(0编辑  收藏  举报