c# 委托初学笔记

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。(定义来自于菜鸟教程

C#委托声明的基本格式:delegate 返回类型 委托类型名 签名(含ref&out)。
C#委托有如下特征:1.必须在被用来创建变量及类型的对象之前声明;2.没有方法主体;
C#委托有两种实例化方法,在如下的代码中可以体现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
delegate int text(int a); //创建委托
namespace Delegate
{
    class Program
    {

        int aab(int a)
        {
            a += 1;
            return a;
        }
        int abb(int a)
        {
            a += 2;
            return a;
        }
        static void Main(string[] args)
        {
            int a = 1;
            Program abc = new Program();
            text ab = new text(abc.aab); //一般的实例化格式
            text ba = abc.abb; //默认的实例化格式
            Console.WriteLine("{0}",ab(a));
            Console.WriteLine("{0}", ba(a));
            Console.ReadLine();
        }
    }
}

C#委托的多播(multicasting)
C#委托的多播,在有的书上也被称作委托的组合,委托对象可使用 “+” 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。”-” 运算符可用于从合并的委托中移除组件委托。,在如下的代码中可以体现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
delegate int text(ref int a); //创建委托
namespace Delegate
{
    class Program
    {

        int aab(ref int a)
        {
            a += 1;
            return a;
        }
        int abb(ref int a)
        {
            a += 2;
            return a;
        }
        static void Main(string[] args)
        {
            int  a = 1;
            Program abc = new Program();
            text aabb;
            text ab = new text(abc.aab); //一般的实例化格式
            text ba = abc.abb; //默认的实例化格式
            aabb = ab;
            aabb += ba; //委托的多播
            Console.WriteLine("{0}",aabb(ref a));
            Console.ReadLine();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值