using System.Reflection;
public class TestDelegate {
public delegate void MyDel();
MyDel delegate1;
MyDel delegate2 = new MyDel(() => { });
MyDel delegate3;
public TestDelegate()
{
delegate1 = Callback;
delegate3 = () => { };
}
void Callback()
{
Console.WriteLine("d1");
}
void Callback2()
{
Console.WriteLine("delx");
}
public void Foo()
{
//Test1
if (delegate1.Target == this)
{//true
Console.WriteLine("delegate1.Target==this");
}
//Test2
//下面两例说明,lambda表达式不属于当前对象
//lambda表达式是被编译器单独生成了一个对象
if (delegate2.Target == this)
{//false
Console.WriteLine("delegate2.Target==this");
}
if (delegate3.Target == this)
{//false
Console.WriteLine("delegate3.Target==this");
}
//Test3
if (delegate1.GetType().IsSubclassOf(typeof(Delegate)))
{//true
Console.WriteLine("yes");
}
//Test4
DelFunc(delegate1);
//Test5
Idelegate delx = new MyDelegate(this, "Callback2");
delx.Method.Invoke(delx.Target, null);
}
//使用抽象基类作参数,面向抽象编程
void DelFunc(Delegate callback)
{
callback.Method.Invoke(callback.Target, null);
}
}
/// <summary>
/// 模拟System.Delegate机制
/// </summary>
public abstract class Idelegate
{
public MethodInfo Method;
public object Target;
protected Idelegate(object target, string method)
{
}
}
public class MyDelegate : Idelegate
{
public MyDelegate(object target, string method) : base(target, method)
{
Target = target;
Method = target?.GetType().GetMethod(method, BindingFlags.Instance| BindingFlags.Public|BindingFlags.NonPublic);
}
}
【复习】C# 委托
于 2022-08-15 17:31:14 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)