C# 委托的使用方法

委托的使用场景积累:
1、无继承关系的两个窗体,窗体(A)唤醒另一个窗体(B),该窗体B需要用到窗体A中某个自定义控件的公有方法时,在dlg.show()之前注册委托



先在一个类中声名委托
delegate string TestDelegate(); //参数要和方法参数对应
delegate string TestDelegateReturnString(string value); //调用GetValue时的委托
public class TestSpace
{
    public TestSpace(){

        }
    public string GetValue(string value)
    {
        return value;
    }
    public string GetMethod1()
    {
        return "Method1";
    }
    public string GetMethod2()
    {
        return "Method2";
    }
}

private void button2_Click(object sender, EventArgs e)
{

    TestSpace obj = new TestSpace();

    //实例化TestDelegate委托,调用委托中的GetValue方法
    TestDelegateReturnString method = (TestDelegateReturnString)Delegate.CreateDelegate(typeof(TestDelegateReturnString), obj, "GetValue"); 
    //其实委托的好处就是方法可以是动态创建的,GetValue可以作为参数传进来

    Console.WriteLine(method.Method.ToString()); //获取当前委托调用的方法
            
    Console.WriteLine(obj.GetValue("TestObjGetValue")); //用实例化对象调用,只能调用指定的方法。

    Console.WriteLine(method.Invoke("TestDelegateRuturnString-method")); //委托调用方法



    TestDelegate method1 = new TestDelegate(obj.GetMethod1); //另一种创建委托的方法 - 调用某个具体方法            
    TestDelegate method2 = new TestDelegate(obj.GetMethod2);
    //创建委托链
    TestDelegate chain = null;
    chain += method1;
    chain += method2;

    //委托数组  数组中的元素使用委托链
    Delegate[] arr = chain.GetInvocationList();

    //遍历委托链
    foreach (TestDelegate item in arr)
    {
        try
        {
            Console.WriteLine(item());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值