zoukankan      html  css  js  c++  java
  • Func(Of T, TResult) 委托

    在Action<Of T>基础上增加了返回值,其参数原型如下:

    public delegate TResult Func<in T, out TResult>(
        T arg
    )

    /*
    In T
    此委托封装的方法的参数类型。

    该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。

    Out TResult
    此委托封装的方法的返回值类型。

    该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。

    */ 

    以前Delegate方法:

    using System;
    using System.Windows.Forms;

    public delegate string DisplayMessage(string message);

    public class testTestDelegate
    {
        public static void Main()
        {
            DisplayMessage showMethod = DisplayToWindow;
            Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
            Console.ReadLine();
        }
        public static string DisplayToWindow(string strName)
        {
            MessageBox.Show("Antiquity Way:Hello World," + strName);
            
            return ("Antiquity Way:Hello World," + strName);
        }

    Func方法:

    using System;
    using System.Windows.Forms;

    public class testTestDelegate
    {
       public static void Main()
       {
          Func<string,string> showMethod = DisplayToWindow;
          Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
          Console.ReadLine();
       }
       public static string DisplayToWindow(string strName)
       {
          MessageBox.Show("Action Way:Hello World," + strName);
          
          return ("Action Way:Hello World," + strName);
       }

     更简化方法(Func还可以传递多个参数,请查阅MSDN):

    using System;
    using System.Windows.Forms;

    public class testTestDelegate
    {
       public static void Main()
       {
          Func<string,string> showMethod = s =>{ 
                                    MessageBox.Show("Action Way:Hello World," + s); 
                                    return ("Action Way:Hello World," + s); 
                                    };
          
          string strName = "ZHANGPS";
                
          Console.WriteLine(showMethod(strName));
          Console.ReadLine();
       }

    转自:http://msdn.microsoft.com/zh-cn/library/bb549151.aspx

  • 相关阅读:
    彻底卸载网易UU网游加速器的方法
    OO之策略模式
    android锁屏和finish()后activity生命周期的变化
    ARTS打卡计划第6周-TIPS-多台服务器免密码登录
    ARTS打卡计划第6周-REVIEW-超越编码的避免项目失败的软技能
    ARTS打卡计划第6周-ALGORITHM
    ARTS打卡计划第5周-SHARE-java构建树形结构
    ARTS打卡计划第5周-TIPS
    ARTS打卡计划第5周-REVIEW-SpringBoot的api版本化实践
    ARTS打卡计划第5周-ALGORITHM
  • 原文地址:https://www.cnblogs.com/zhangpengshou/p/2266507.html
Copyright © 2011-2022 走看看