c# 委托 delegate

本人在学习C#,遇到了delegate,故上网搜寻相关文档,现在已经理解了它的用途了。整理如下:

用途:

        简单的来说,委托就是用来执行那些和定义的委托有同样类型参数和返回值的方法。

例子:

        比如定义委托:public delegate void MyDeleteGate();

那么只要是返回值是void, 没有输入参数的方法(不管这个方法是定义在哪里,不管是静态的还是实例的)都可以由这个交由这个委托来执行。

又比如定义下面这个委托:public delegate string MySecondDeleteGate(string parameter1, double parameter2);

那么只要是返回值是string, 第一个参数是string, 第二个是double的方法(不管这个方法是定义在哪里,不管是静态的还是实例的)都可以由这个交由这个委托来执行。

下面是简单的例子:

namespace Utils
{

    //定义一个委托,委托的名字是 MyDeleteGate
    public delegate void MyDeleteGate();

    //定义一个委托,委托的名字是 MySecondDeleteGate
    public delegate string MySecondDeleteGate(string parameter1, double parameter2);
}

 实现一下方法,为了交由委托来执行:

namespace Utils
{
    public class DelegateMethods
    {
        public void initial()
        {
            Console.WriteLine("Initial method!");
        }

        public static void StaticMethod()
        {
            Console.WriteLine("It is StaticMethod method!");
        }

        public string Check(string parameter, double value)
        {
            //do some thing accordin these input parmeters
            Console.WriteLine("Check method!");
            return "This is check method";
        }

        public static string StaticCheck(string parameter, double value)
        {
            //do some thing accordin these input parmeters
            Console.WriteLine("StaticCheck method!");
            return "This is a static check method";
        }
    }
}

下面代码演示如何使用:

namespace Utils
{
    public class Test
    {
        static void Main(string[] args)
        {
            DelegateMethods delegateMethods = new DelegateMethods();
            MyDeleteGate myDeleteGate = new MyDeleteGate(delegateMethods.initial);//委托实例方法
            myDeleteGate += DelegateMethods.StaticMethod;//委托静态方法
            myDeleteGate += finish;//委托调用一个定义在其它对象上的方法

            myDeleteGate();//执行委托

            MySecondDeleteGate mySecondDeleteGate = new MySecondDeleteGate(delegateMethods.Check);//委托实例方法
            mySecondDeleteGate += DelegateMethods.StaticCheck;//委托静态方法
            mySecondDeleteGate += FinishCheck;//委托调用一个定义在其它对象上的方法

            string value = mySecondDeleteGate("Test", 12.3);//执行委托
        }

        private static void finish()
        {
            Console.WriteLine("finish method");
        }

        private static string FinishCheck(string par, double va)
        {
            Console.WriteLine("finish method");
            return "ok";
        }
    }
}

上面这个就是委托的简单使用流程。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值