那是......奇怪而令人困惑.如果您只需要一个方法的实现... 使用方法(可能是一个虚方法).至于接口方面,部分点代表的是可以替代多种不同的实现.
如果我不得不总结一下:
委托类型非常类似于只暴露单个方法的接口,委托实例非常类似于实现该接口的类的实例- 只是具有大量的编译器性感,使得它非常容易写,即
x => 2 * x,没有(有时)需要实例.
一个代表也有一些其他有用的技巧events(多播等),但这听起来与文章的上下文无关.
一个类可能需要多个方法的实现.
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)
在上面的例子中,只有接口公开的方法的单个实现.