gpt4 book ai didi

c# - 何时使用委托(delegate)而不是接口(interface)

转载 作者:太空狗 更新时间:2023-10-29 21:05:55 25 4
gpt4 key购买 nike

根据这个article ,它说:

Use a delegate in the following circumstances:

  • A class may need more than one implementation of the method.

Use an interface in the following circumstances:

  • A class only needs one implementation of the method.

有人能给我解释一下吗?

最佳答案

A class may need more than one implementation of the method.

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;
}

上面例子中的PerformCalculation_1、PerformCalculation_2是PerformCalculation的多重实现

A class only needs one implementation of the method

interface IDimensions 
{
float Length();
}

class Box : IDimensions
{
float Length()
{
return lengthInches;
}
}

在上面的示例中,接口(interface)公开的方法只有一个实现。

关于c# - 何时使用委托(delegate)而不是接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11204598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com