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()
#####
愿你一寸一寸地攻城略地,一点一点地焕然一新
#####
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南