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

C# 委托

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

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# 委托” 的相关文章

类、对象、属性、方法

类:具有同种属性的对象称为类,是个抽象的概念。比如说:汽车、人、狗、房子;对象:类实例化后形成对象,具体的概念。如:小明是人的实例化;属性:用来描述具体某个对象的特征的是属性,是静态的。比如:小明身高1.8米多,体重50kg都是属性;方法:每个对象有它们自己的行为或者是使用它们的方法,比如说一只狗会...

C#的类型系统

C#的类型系统

C#的五大数据类型:    类(Class)    结构体(Structures)    枚举(Enumerations)    接口(In...

C# 使用不安全的代码

首先需要在 项目->属性->生成 中勾选允许不安全代码下面的代码使用了指针,通过指针修改结构体的成员namespace _20200320 {     class Program   &nbs...

C# 正则表达式(1)

C# 正则表达式(1)

用于匹配输入文本的模式string s = "this is a test!"; string res = Regex.Replace(s, "^",&nbs...

C# 正则表达式(2)

// pattan = @"[^ahou]"; 表示匹配除ahou之外的字符,^在表示反义 string res4 = Regex.Replace(s, @"[^ahou]",&...

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

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