C#中的委托delegate

Action委托

注意点

  1. Action委托只能指向无参数,无返回值的方法

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace study3
{
    class Program
    {
        static void Main(string[] args)
        {
            Action myAction = new Action(SayHello);
            myAction();
            //myAction.Invoke();
        }
        static void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

Func委托

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
 * Func委托——针对有参数和返回值的方法
 */
namespace study_5
{
    class Program
    {
        static void Main(string[] args)
        {
            Cal cal = new Cal();
            Func<int, int, int> func1 = new Func<int, int, int>(cal.Add);
            int result = func1(2, 3);
            Console.WriteLine(result);
        }
    }

    class Cal
    {
        public int Add(int n1,int n2)
        {
            return n1 + n2;
        }
    }
}

自定义委托

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
 * Func委托——针对有参数和返回值的方法
 */
namespace study_5
{
    //自定义委托
    public delegate string StrConnect(string str1, string str2);
    class Program
    {
        static void Main(string[] args)
        {
            //自定义委托
            StrTools strTools = new StrTools();
            string str1 = "你好,";
            string str2 = "世界!";
            StrConnect tools = new StrConnect(strTools.StrCon);
            string str3 = tools(str1, str2);
            Console.WriteLine(str3);
        }
    }
    class StrTools
    {
        public string StrCon(string str1, string str2)
        {
            return str1 + str2;
        }
    }
}

应该适时地使用接口(interface)取代一些对委托的使用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值