委托及多播委托

c#中的委托类似于c  c++中的指针,委托就是概括了方法的签名和返回值类型 ,委托可以理解为定义的一个新的类。

所以在可以定义类的任何地方都可以定义委托,也可以在委托的定义上加访问修饰符 public  private 等

1、定义一个委托  类似于方法的定义

该委托表示的方法有两个long类型参数,返回值类型为double

delegate double TwoLongOp (long first,long second);

定义一个不带参数,返回一个string类型的值的委托

public delegate string GetString();

2、委托的简单使用

 class Program
    {
        private delegate string GetAString();
        static void Main(string[] args)
        {
            int x=30;
            GetAString firstStringMetheod = new GetAString(x.ToString);
            Console.WriteLine("String is {0}", firstStringMetheod());

        }
    }

委托的实例化:

实例化一个GetAString类型的firstStringMethod变量

GetAString firtStringMethod = new GerAString(x.ToString);

也可以 GetAString firtStringMethod =x.ToString;

3、带参委托和委托数组使用

 <pre name="code" class="csharp">class MathsOperations
    {
        public static double MultiplyByTwo(double value)
        {
            return value * 2;
        }
        public static double Square(double value)
        {
            return value * value;
        }
    }

 
 class Program
    {    
        delegate double DoubleOp(double x);
        static void Main(string[] args)
        {         
            DoubleOp[] operations =
            {
                MathsOperations.MultiplyByTwo,
                MathsOperations.Square
            };

            for (int i = 0; i < operations.Length; i++)
            {
                Console.WriteLine("using operations [{0}]", i);
                ProcessAndDisNum(operations[i], 2.0);
                ProcessAndDisNum(operations[i], 8);
                ProcessAndDisNum(operations[i], 16);
                Console.WriteLine();
            }

        }
       static void ProcessAndDisNum(DoubleOp action, double value)
        {
            double result = action(value);
            Console.WriteLine("Value is {0} ,result of operation is {1}", value, result);
        }
    }
泛型Action<T>委托表示可以引用一个void返回类型的方法,泛型Func<T>允许调用返回值的方法。最多可以传递16个参数类型和一个返回类型。Func<in T,out Result>表示一个带参的方法

Func<double, double>[] operations=

{

MathOperations.MultiplyByTwo,

MathOperations.Squre

};

static void ProcessAndDisNum(<span style="font-size:18px;">Func<double, double> </span>action, double value)

4、多播委托的使用

如果调用多播委托就可以按顺序连续调用多个方法,但是,多播委托的签名必须返回void ,否则,只能得到委托调用的最后一个方法的结果

多播委托可以使用+= -= 运算符,用于在委托中添加或删除方法调用

Action<double><pre name="code" class="html" style="font-size:18px;">operations 
= MathsOperations.MultiplyByTwo;operations += MathsOperations.Square;
ProcessAndDisNum(operations,2);
ProcessAndDisNum(operations,8);

 
使用多播委托时,如果其中一个方法抛出异常,整个迭代就会停止。 

为了避免这个问题可以自己迭代方法列表

Delegate[] delegates=operations .GetInvocationList();
foreach(Action d in delegates)
{

}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值