何时使用代理而不是接口

Ric*_*ard 6 c# delegates interface

根据这篇文章,它说:

在以下情况下使用代理:

  • 一个类可能需要多个方法的实现.

在以下情况下使用接口:

  • 一个类只需要该方法的一个实现.

谁可以给我解释一下这个?

Mar*_*ell 6

那是......奇怪而令人困惑.如果您只需要一个方法的实现... 使用方法(可能是一个虚方法).至于接口方面,部分代表的是可以替代多种不同的实现.

如果我不得不总结一下:

委托类型非常类似于只暴露单个方法的接口,委托实例非常类似于实现该接口的类的实例- 只是具有大量的编译器性感,使得它非常容易写,即x => 2 * x,没有(有时)需要实例.

一个代表也有一些其他有用的技巧events(多播等),但这听起来与文章的上下文无关.


Adi*_*dil 5

一个类可能需要多个方法的实现.

public delegate int PerformCalculation(int x, int y);

void SomeMethod()
{
    PerformCalculation PerformCalculation_1 = myDelegateFun_1;
    PerformCalculation PerformCalculation_2 = myDelegateFun_2;
    PerformCalculation_1(5, 3);
    PerformCalculation_2(5, 3);      
}

private int myDelegateFun_1(int x, int y)
{
    return x + y;
}
private int myDelegateFun_2(int x, int y)
{
    return x + y;
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例PerformCalculation_1中,PerformCalculation_2是PerformCalculation的多个实现

A class only needs one implementation of the method
Run Code Online (Sandbox Code Playgroud)

 

interface IDimensions 
{
   float Length();
}

class Box : IDimensions 
{
   float Length() 
   {
       return lengthInches;
   }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,只有接口公开的方法的单个实现.