zoukankan      html  css  js  c++  java
  • C#-委托

    一、委托是什么?

      委托一般可以看作是持有一个或多个方法的对象。可以把委托看做是对象,其和我们使用一个对象的过程一样。

      声明->创建委托对象->给委托赋值->调用委托。  

      关于委托还有另一种理解,我们可以把委托类比为C/C++中的函数指针这一概念。只是委托是类型安全的。函数指针就是

    指向函数入口地址的一个地址变量。我们可以随便更改指针指向的地址,以达到对不同函数的调用。同样我们可以更改委托的赋值

    方法可以执行不同的方法。

      函数指针特别适合用于回调函数,可以在函数执行时再判断函数指针指向的函数。委托也可以在执行的时候再决定指向哪一个方法。

      使用委托的实例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
     
    
    namespace DelegateDemo
    {
        delegate void MyDel(int value);
        class Program
        {
            void PrintLow(int value)
            {
                Console.WriteLine("The low value is {0}", value);
            }
    
            void PrintHigh(int value)
            {
                Console.WriteLine("The high value is {0}", value);
            }
    
            static void Main(string[] args)
            {
                Program program = new Program();
                //MyDel del;
                Action <int> del = null;
                Random random = new Random();
                int randomValue = random.Next(99);
                if (randomValue < 50)
                {
                    //del = delegate (int x)
                    //      {
                    //          Console.WriteLine("Low value{0}", x);
                    //      };
                    del =(int x)=>
                    {
                        Console.WriteLine("Low value:{0}", x);
                    };
    
                    //del = x => { };  //匿名方法+Lambda表达式
                }
                else
                {
                    del = delegate (int x)
                    {
                        Console.WriteLine("High value{0}", x);
                    };
                }
                del(randomValue);
                Console.ReadKey();
            }
        }
    }

    二、泛型委托

      CLR环境中给我们内置了几个常用委托Action、 Action<T>、Func<T>、Predicate<T>,一般我们要用到委托的时候,尽量不要自己再定义一 个委托了,

    就用系统内置的这几个已经能够满足大部分的需求,且让代码符合规范。 

      例如上面代码的两种定义:public delegate void MyDel(int x) ; //自己定义的一种委托类型,返回值为void,一个int类型参数,

    其实系统已经帮我们定义了。我们完全可以采用  Action <T>  泛型来定义: Action <int> del = null 。

      其余也类似,关于返回值。

    三、匿名方法

       上面的代码既有关于匿名方法的介绍也有Lambda表达式的一般使用方式。

       MyDel del = delegate (int x){ Console.WriteLine(""); };

            MyDel del  =   x  => x + 1 ;

  • 相关阅读:
    多多挣钱,多多攒钱。
    平安鸿运英才少儿教育金保障计划
    沙河订奶
    排序算法--参考
    《程序设计基础》考试大纲 复习-C语言
    There is no Action mapped for namespace [/demo1] and action name [doLogin] associated with context path [/SSO_same_domain]
    Android报错 The connection to adb is down, and a severe error has occured.
    解析库beautifulsoup
    request模块使用
    爬虫基本原理
  • 原文地址:https://www.cnblogs.com/nyqm/p/10073495.html
Copyright © 2011-2022 走看看