📜  C# 中的委托与接口

📅  最后修改于: 2021-09-13 02:46:37             🧑  作者: Mango

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

例子:

// C# program to illustrate Delegates
using System;
  
class GFG {
  
    // 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 GFG class
        GFG o = new GFG();
  
        // 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 GeeksforGeeks..!");
    }
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating object
        Geeks o = new Geeks();
  
        // calling method
        o.display();
    }
}

输出:

Welcome to GeeksforGeeks..!

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

Delegate Interface
It could be a method only. It contains both methods and properties.
It can be applied to one method at a time. If a class implements an interface, then it will implement all the methods related to that interface.
If a delegate available in your scope you can use it. Interface is used when your class implements that interface, otherwise not.
Delegates can me implemented any number of times. Interface can be implemented only one time.
It is used to handling events. It is not used for handling events.
It can access anonymous methods. It can not access anonymous methods.
When you access the method using delegates you do not require any access to the object of the class where the method is defined. When you access the method you need the object of the class which implemented an interface.
It does not support inheritance. It supports inheritance.
It can wrap static methods and sealed class methods It does not wrap static methods and sealed class methods..
It created at run time. It created at compile time.
It can implement any method that provides the same signature with the given delegate. If the method of interface implemented, then the same name and signature method override.
It can wrap any method whose signature is similar to the delegate and does not consider which from class it belongs. A class can implement any number of interfaces, but can only override those methods which belongs to the interfaces.