当前位置:首页 > 代码相关 > 正文内容

C# 委托

admin5年前 (2020-03-27)代码相关8668

Action和Func是.NET类库的内置委托,以简便使用。

image.png

image.png

Func有17个重载

image.png

还可以使用delegate关键字创建委托


下面的代码展示了这三种使用委托的方法

namespace _20200327
{
    public delegate int Delga(int a, int b);
    class Program
    {
        static void Main(string[] args)
        {
            Calculate cal = new Calculate();
            Action action = new Action(cal.Report);
            action();

            Func<int, int, int> funcAdd = new Func<int, int, int>(cal.Add);
            int a = 100;
            int b = 200;
            int c = 0;
            c = funcAdd(a, b);
            Console.WriteLine(c);

            Delga delgaSub = new Delga(cal.Sub);
            c = delgaSub(a, b);
            Console.WriteLine(c);


            Console.ReadKey();
        }
    }

    class Calculate
    {
        public void Report()
        {
            Console.WriteLine("3个方法");
        }
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Sub(int a,int b)
        {
            return a - b;
        }
    }
}


扫描二维码推送至手机访问。

版权声明:本文由lovedm.club发布,如需转载请注明出处。

本文链接:https://lovedm.club/?id=23

标签: C#
分享给朋友:

“C# 委托” 的相关文章

C#事件_Sample_2

事件的拥有者与事件的响应者是分开的情况+=是事件订阅操作符,左边是事件,右边是事件处理器。using System; using System.Windows.Forms; /// <summary> /// 事件的拥有者和事件的响应者是...

C# 与文件相关的几个类(1)

C# 与文件相关的几个类(1)

C# 与文件访问相关的常用的类:File类、Directory类、Path类、FileInfo类、DirectoryInfo类、FileSystemInfo类、FileSystemWatcher类以上几个类均在System.IO命名空间下。挨个说吧:File类:静态类,只有静态方法,用于移...

C# 与文件相关的几个类(2)

Directory类:静态类,主要处理文件目录。方法:CreateDirectory(String)在指定路径中创建所有目录和子目录,除非它们已经存在。返回值是一个DirectoryInfo对象Delete(String)从指定路径删除空目录。无返回值。Exists(String)确定给定路径是否引...

C#(或者Java)反转数组

将原数组反转,如[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]反转后变为[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]因为数组是引用类型,所以直接在方法中处理即可,C#和Java写法一样,如下:      &nb...

C# Stack堆栈

Stack代表了一个先入后出的对象集合。有以下常用方法:表 3Clear()从 Stack 中移除所有对象。Contains(Object)确定某元素是否在 Stack 中。CopyTo(Array, Int32)从指定的数组索引处开始,将 Stac...

C# 返回值是接口的方法

今天写PIE二次开发加载栅格数据的时候发现类中方法的返回值是接口,之前没怎么写过,在此记录一下。在例子中设计一个接口 ICalculate ,接口中有两个方法, Add() 和 Div() 分别为加法和减法的功能,均有两个参数,参数和返回值的类型都是int类型。设计一个名为Calculat...