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();
        }
    }
}
相关推荐
彧azz2 小时前
图的存储结构详解:邻接矩阵的原理、实现与应用
开发语言·数据结构·学习·php
嵌入式学习菌2 小时前
Modbus‑RTU 数据类型分析
开发语言·单片机·bug
matlab代码3 小时前
基于matlab数字图像处理的指纹识别系统【源码68期】
开发语言·matlab
matlab代码4 小时前
基于matlab的水果识别系统(苹果香蕉菠萝梨桃子)【源码65期】
开发语言·matlab
wuyk5554 小时前
从零吃透 MQTT 通信|第 8 章 FreeRTOS 多任务架构下 MQTT 工程架构,任务拆分、队列解耦、临界区保护
c语言·开发语言·stm32·学习·架构
weixin199701080164 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
尘客-追梦4 小时前
Day 01:插件化之前,先看清 ABI 这堵墙
开发语言·c++·qt
持敬chijing5 小时前
Python-数据类型-列表
开发语言·python·青少年编程
写后端的胖头鱼6 小时前
【高频面试题】Java 基础类型 + 包装类 + String 互相转换
java·开发语言
matlab代码6 小时前
基于matlab自助水果超市水果识别收费系统(GUI界面)【源码67期】
开发语言·matlab