C#委托的原理, 和 实际用法(怪物死亡后委托更新人物经验和UI界面显示)

C# 委托各种用法, 委托就相当于 一个变量类型, 类似INT ,INT用来装整数, 委托用来装 函数, 按照 返回值,参数 规定的格式来装

基本原理:

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

namespace 委托
{
    class Program
    {
        static void Main(string[] args)
        {
            Action ac1 = fun1;//无返回值无参数
            ac1();
            Action<int> ac2 = fun2;//无返回值,有1参数
            ac2(1);
            Action<int, int> ac3 = fun3;//无返回值,有2参数
            ac3(2,3);
            Func<int> f1 = fun4;//有1个返回值, 无参数
            f1();
            Func<int,int> f2 = fun5;//有1个返回值, 1个参数
            f2(1);
            Func<int, int,int> f3 = fun6;//有1个返回值, 2个参数
            f3(1,1);
        }

        static void fun1()
        {

        }
        static void fun2(int a)
        {

        }
        static void fun3(int a, int b)
        {

        }
        static int fun4()
        {
            return 1;
        }
        static int fun5(int a)
        {
            return 1;
        }
        static int fun6(int a,int b)
        {
            return 1;
        }
    }
}

实际项目用法: 怪物死亡后委托更新人物经验和UI界面显示

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

namespace 怪物死亡委托
{
    class Monster
    {
        public Action<int> deadDoSomthing;
        public void Dead()
        {
            int xp = 1000;

            Console.WriteLine("怪物死了");
            if (deadDoSomthing != null)
            {
                deadDoSomthing(xp);
            }
        }
    }

    class Player
    {
        public void AddXp(int xp)
        {
            Console.WriteLine("人物增加经验{0}",xp);
        }
    }

    class UI
    {
        public void UpgradeUI(int xp)
        {
            Console.WriteLine("界面更新经验值{0}", xp);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Monster m = new Monster();
            Player p = new Player();
            UI u = new UI();
            m.deadDoSomthing += p.AddXp;
            m.deadDoSomthing += u.UpgradeUI;

            m.Dead();
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sky6595418

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值