c#Action委托和Func委托

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Action委托
{
    internal class Program
    {
        static void PrintString()
        {
            Console.WriteLine("hello world.");
        }
        static void PrintInt(int i)
        {
            Console.WriteLine(i);
        }
        static void PrintString(string str)
        {
            Console.WriteLine(str);
        }
        static void PrintDoubleInt(int i1,int i2)
        {
            Console.WriteLine(i1 + i2);
        }
        static void Main(string[] args)
        {
            Action a = PrintString;//Action是系统内置(预定义)的一个委托类型,它可以指向一个没有返回值,没有参数的方法
            Action<int> b=PrintInt;//定义了一个委托类型,这个类型可以指向一个没有返回值,有一个int参数的方法

            Action<string> c = PrintString;//定义了一个委托类型,这个类型可以指向一个没有返回值,有一个string参数的方法,因为叫PrintString的方法有两个,在这里系统会自动寻找匹配的方法
            Action<int, int> d = PrintDoubleInt;
            d(34, 23);
            Console.ReadKey();
            //Action可以通过泛型去指定Action指向的方法的多个参数的类型,参数的类型跟Action后面声明的委托类型是对应着的
        }
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Func委托
{
    internal class Program
    {
        static int Test1()
        {
            return 1;
        }
        static int Test2(string str) 
        { 
            Console.WriteLine(str);
            return 100; 
        }
        static int Test3(int i,int j)
        {
            return i + j;
        }
        static void Main(string[] args)
        {
            //Func<int> a = Test1;//func中的泛型类型制定的是 方法的返回值类型
            //Console.WriteLine(a());
            Func<string,int> b=Test2;//func后面可以跟很多类型,最后一个类型是返回值类型,前面的类型是参数类型,参数类型必须跟指向的方法的参数类型按照顺序对应
            Func<int,int,int> a=Test3;//func后面必须指定一个返回值类型,参数类型可以有0-16个,先写参数类型,最后一个是返回值类型
            int res = a(1, 5);
            Console.WriteLine(res);
            Console.ReadKey();
        }
    }
}
相关推荐
爱吃烤鸡翅的酸菜鱼15 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
神仙别闹33 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
向宇it1 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。
游戏·3d·unity·c#·游戏引擎·材质
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发7 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++