委托是一个引用方法的对象,或者可以说它是一个引用类型变量,可以保存对方法的引用。C# 中的委托类似于 C/C++ 中的函数指针。它提供了一种方法来告诉在触发事件时要调用哪个方法。

例子:

// C# program to illustrate Delegates
using System;

class YiibaiDemo {

    // Declaring the delegates
    public delegate void AddVal(int x, int y);

    public void SMeth(int x, int y)
    {
        Console.WriteLine("[190 + 70] = [{0}]", x + y);
    }

    // Main Method
    public static void Main(String[] args)
    {

        // Creating the object of YiibaiDemo class
        YiibaiDemo o = new YiibaiDemo();

        // Creating object of delegate
        AddVal obj = new AddVal(o.SMeth);

        // Pass the values to the method
        // Using delegate object
        obj(190, 70);
    }
}

运行结果:

[190 + 70] = [260]

与类一样,接口可以将方法、属性、事件和索引器作为其成员。但是接口只包含成员的声明。接口成员的实现将由隐式或显式实现接口的类给出。

例子:

// C# program to illustrate the
// concept of interface
using System;

// A simple interface
interface inter {

    // method having only declaration
    // not definition
    void display();
}

// A class that implements the interface
class Geeks : inter {

    // providing the body part of function
    public void display()
    {
        Console.WriteLine("Welcome to Yiibai Yiibai..!");
    }

    // Main Method
    public static void Main(String[] args)
    {

        // Creating object
        Geeks o = new Geeks();

        // calling method
        o.display();
    }
}

运行结果:

Welcome to Yiibai Yiibai..!

以下是 C# 中委托和接口之间的一些区别:

委托 接口
委托可能只是一种方法 接口包含方法和属性
委托可以一次应用于一种方法 如果一个类实现了一个接口,那么它将实现与该接口相关的所有方法。
如果范围内有可用的委托,可以使用它 当类实现接口时使用接口,否则不使用。
委托可以执行任意次数 接口只能实现一次
委托用于处理事件 接口不用于处理事件
委托可以访问匿名方法 接口不能访问匿名方法
当使用委托访问该方法时,不需要对定义该方法的类的对象进行任何访问。 当访问该方法时,需要实现接口的类的对象。
委托不支持继承。 接口支持继承。
委托可以包装静态方法和密封类方法 接口不包装静态方法和密封类方法
委托在运行时创建 接口在编译时创建
委托可以实现与给定委托提供相同签名的任何方法 如果实现了接口的方法,则覆盖同名和签名的方法
委托可以包装任何签名与委托相似的方法,并且不考虑它属于哪个类 一个类可以实现任意数量的接口,但只能覆盖属于这些接口的那些方法