Delegate的Target,Method
生活随笔
收集整理的這篇文章主要介紹了
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()
總結
以上是生活随笔為你收集整理的Delegate的Target,Method的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GBDT算法原理及Python实现
- 下一篇: Manus邀请码,Manus:科技圈新“