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

C# 委托

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

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# WPF程序 显示时间

C# WPF程序 显示时间

例子来源于此视频https://www.bilibili.com/video/av1422127?p=4 此例子是想说明有的类主要使用它的事件namespace Wpf_test {     /// <summary> &...

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

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

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

C# 使用FileStream进行文件复制操作

使用文件流进行操作,如下,其中注释部分是和非注释部分一样的,但是使用using语句是执行完后自动释放内存,而注释部分是手动释放。CopyFile方法中,缓冲区大小设为1024*1024字节,也就是1MB,Read方法和Write方法中,第一个参数都是缓冲区数组,第二个参数都是偏移量,这个量是在缓冲区...

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

Path类,处理文件或路径的类,是一个静态类。方法:PathChangeExtension(String, String)更改路径字符串的扩展名。返回值为string。Combine(String, String)将两个字符串组合成一个路径。GetDirectoryName(String)返回指定路...

偶然想到的一个问题。。。

偶然想到的一个问题。。。

今天突然想C#中,用数组中的Max()方法和直接通过比较获取最大值的时间谁快,于是试了试:       static void Main(string[] args)   &nb...

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...