zoukankan      html  css  js  c++  java
  • 委托的一些笔记

    1、理解委托的一种好方式是把委托视为给方法的签名和返回类型指定名称;

    2、定义委托基本上是定义一个新类,所以可以在定义类的任何相同地方定义委托,也就是说可以在一个类的内部定义委托,也可以在任何类的外部定义委托,还可以在命名空间中把委托定义为顶级对象;

    3、使用委托时,也类似使用类,首先要定义委托(包括访问修饰符、返回值、参数):

      ①public delegate string InMethodInvoker() ---------返回为string,无参数

      ②public delegate void OutPut(int i)  -----------返回void,存在一个int型参数

    4、方法必须和委托定义时的签名的一致

      ① 

    int i=9;
    
    InMethodInvoker inMethodInvoker = new InMethodInvoker(i.ToString);

    Console.WriteLine($"String is { inMethodInvoker()}");

     ②

    public static void MyMethod(int i)
    {
         Console.WriteLine($"String is {i.ToString()}");
    }
    
    static void Main(string[] args)
    {
         OutPut output = new OutPut(MyMethod);
       output (999); 

       Console.ReadKey();
    }

    5、为了减少输入量,在需要委托实例的每个位置可以只传送地址的名称,称为委托推断,上述委托实例化可以改为:

    InMethodInvoker inMethodInvoker = i.ToString;

    OutPut output = MyMethod ;

    6、委托的简单示例,细细品吧

     1 using System;
     2 
     3 namespace DelegateConsole
     4 {
     5     class MathOperations
     6     {
     7         public static double MultiplyByTwo(double value) => value * 2;
     8         public static double Square(double value) => value * value;
     9     }
    10 
    11     class Program
    12     {
    13         delegate double DoubleOp(double x);
    14         static void Main(string[] args)
    15         {
    16             DoubleOp[] operations =
    17             {
    18                 MathOperations.MultiplyByTwo,
    19                 MathOperations.Square
    20             };
    21 
    22             for (int i=0; i < operations.Length; i++)
    23             {
    24                 Console.WriteLine($"Using operations[{i}]:");
    25                 ProcessAndDisplayNumber(operations[i], 2.0);
    26                 ProcessAndDisplayNumber(operations[i], 7.94);
    27                 ProcessAndDisplayNumber(operations[i], 1.414);
    28                 Console.WriteLine();
    29             }
    30             Console.ReadKey();
    31         }
    32 
    33         private static void ProcessAndDisplayNumber(DoubleOp action, double value)
    34         {
    35             double result = action(value);
    36             Console.WriteLine($"Value is {value},result of operation is {result}");
    37         }
    38     }
    39 }
    
    
     
  • 相关阅读:
    数据结构与算法--递归
    未能加载文件或程序集“ .....WebUI ”或它的某一个依赖项,试图加载格式不正确的程序
    PLSQL设置细节
    Oracle安装:64位电脑安装64位Oracle、PLSQL步骤
    C# JS 单例
    Method not found : Void System.Data.Objects.ObjectContextOptions.set_UseConsistentNullReferenceBehavior(Boolean)
    Webservice 65535 错误
    js queue dequeue clearQueue stop
    解决Get请求的长度限制
    站点图标favicon.ico
  • 原文地址:https://www.cnblogs.com/zuiailiuruoying/p/13305972.html
Copyright © 2011-2022 走看看