zoukankan      html  css  js  c++  java
  • C#的委托 Action<>和Func<>

    其实他们两个都是委托【代理】的简写形式。

    一、【action<>】指定那些只有输入参数,没有返回值的委托

    Delegate的代码:

    [csharp] 

    public delegate void myDelegate(string str); 

    public static void HellowChinese(string strChinese) 

        Console.WriteLine("Good morning," + strChinese); 

        Console.ReadLine(); 

    myDelegate d = new myDelegate(HellowChinese); 

    d("Mr wang"); 

    用了Action之后呢:

    [csharp] 

    public static void HellowChinese(string strChinese) 

        Console.WriteLine("Good morning," + strChinese); 

        Console.ReadLine(); 

    Action<string> action = HellowChinese; 

    action("Spring."); 

    就是相当于省去了定义委托的步骤了。

    二、func<> 这个和上面的那个是一样的,区别是这个有返回值!

    [csharp]  www.2cto.com

    public static string HelloEnglish(string strEnglish) 

        return "Hello." + strEnglish; 

    Func<string, string> f = HelloEnglish; 

    Console.WriteLine(f("Srping ji")); 

    Console.ReadLine(); 

     

     

    unc,Action 的介绍及其用法

    Func是一种委托,这是在3.5里面新增的,2.0里面我们使用委托是用Delegate,Func位于System.Core命名空间下,使用委托可以提升效率,例如在反射中使用就可以弥补反射所损失的性能。
    Action<T>和Func<T,TResult>的功能是一样的,只是Action<T>没有返类型,

    Func<T,T,Result>:有参数,有返回类型

    Action,则既没有返回也没有参数,

    Func<T,TResult> 的表现形式分为以下几种:

    1。Func<T,TResult>

    2。Func<T,T1,TResult>

    3。Func<T,T1,T2,TResult>

    4。Func<T,T1,T2,T3,TResult>

    5。Func<T,T1,T2,T3,T4,TResult>

    分别说一下各个参数的意义,TResult表示 委托所返回值 所代表的类型, T,T1,T2,T3,T4表示委托所调用的方法的参数类型,

    以下是使用示例:

    Func<int, bool> myFunc = null;//全部变量

    myFunc = x => CheckIsInt32(x); //给委托封装方法的地方 使用了Lambda表达式

    private bool CheckIsInt32(int pars)//被封装的方法
            {
                return pars == 5;
            }

      bool ok = myFunc(5);//调用委托

    MSDN:http://msdn.microsoft.com/zh-cn/library/bb534303(VS.95).aspx

    但是如果我们需要所封装的方法不返回值,增么办呢?就使用Action!

    可以使用 Action<T1, T2, T3, T4>委托以参数形式传递方法,而不用显式声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有四个均通过值传递给它的参数,并且不能返回值。(在 C# 中,该方法必须返回 void。在 Visual Basic 中,必须通过 SubEnd Sub 结构来定义它。)通常,这种方法用于执行某个操作。

    使用方法和Func类似!

    MSDN:http://msdn.microsoft.com/zh-cn/library/bb548654(VS.95).aspx

    Action:既没有返回,也没有参数,使用方式如下:

    Action action = null;//定义action

    action =  CheckIsVoid;//封装方法,只需要方法的名字

    action();//调用

    总结:使用Func<T,TResult>和Action<T>,Action而不使用Delegate其实都是为了简化代码,使用更少的代码达到相同的效果,不需要我们显示的声明一个委托,Func<T,TResult>的最后一个参数始终是返回类型,而Action<T,TResult>是没有返回类型的,而Action是没有返回类型和参数输入的。

  • 相关阅读:
    每天一道LeetCode--141.Linked List Cycle(链表环问题)
    每天一道LeetCode--119.Pascal's Triangle II(杨辉三角)
    每天一道LeetCode--118. Pascal's Triangle(杨辉三角)
    CF1277D Let's Play the Words?
    CF1281B Azamon Web Services
    CF1197D Yet Another Subarray Problem
    CF1237D Balanced Playlist
    CF1239A Ivan the Fool and the Probability Theory
    CF1223D Sequence Sorting
    CF1228D Complete Tripartite
  • 原文地址:https://www.cnblogs.com/suizhikuo/p/3652091.html
Copyright © 2011-2022 走看看