c# - 委托(delegate)们,为什么?

标签 c# delegates

<分区>

Possible Duplicates:
When would you use delegates in C#?
The purpose of delegates

我看到很多关于使用委托(delegate)的问题。我仍然不清楚在哪里以及为什么要使用委托(delegate)而不是直接调用方法。

我多次听到这句话:“然后可以将委托(delegate)对象传递给可以调用引用方法的代码,而不必在编译时知道将调用哪个方法。”

我不明白这种说法是正确的。

我编写了以下示例。假设您有 3 个具有相同参数的方法:

   public int add(int x, int y)
    {
        int total;
        return total = x + y;
    }
    public int multiply(int x, int y)
    {
        int total;
        return total = x * y;
    }
    public int subtract(int x, int y)
    {
        int total;
        return total = x - y;
    }

现在我声明一个委托(delegate):

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

现在我可以更进一步,声明一个处理程序来使用这个委托(delegate)(或直接使用您的委托(delegate))

调用委托(delegate):

MyClass f = new MyClass();

Operations p = new Operations(f.multiply);
p.Invoke(5, 5);

或调用handler

f.OperationsHandler = f.multiply;
//just displaying result to text as an example
textBoxDelegate.Text = f.OperationsHandler.Invoke(5, 5).ToString();

在这两种情况下,我看到指定了我的“乘法”方法。为什么人们使用“在运行时更改功能”或上面的短语?

如果每次声明委托(delegate)时都需要一个方法来指向它,为什么还要使用委托(delegate)?如果它需要一个方法来指向,为什么不直接调用那个方法呢?在我看来,我必须编写更多代码才能使用委托(delegate),而不仅仅是直接使用函数。

谁能给我一个真实世界的情况?我完全糊涂了。

最佳答案

在运行时更改功能不是委托(delegate)完成的。

基本上,delegates 为您省去了大量的输入工作。

例如:

class Person
{
    public string Name { get; }
    public int Age { get; }
    public double Height { get; }
    public double Weight { get; }
}

IEnumerable<Person> people = GetPeople();

var orderedByName = people.OrderBy(p => p.Name);
var orderedByAge = people.OrderBy(p => p.Age);
var orderedByHeight = people.OrderBy(p => p.Height);
var orderedByWeight = people.OrderBy(p => p.Weight);

在上面的代码中,p => p.Name , p => p.Age等都是计算结果为 Func<Person, T> 的 lambda 表达式委托(delegate)(其中 T 分别是 stringintdoubledouble )。

现在让我们考虑如何在没有委托(delegate)的情况下实现上述目标。而不是拥有 OrderBy方法采用委托(delegate)参数,我们将不得不放弃通用性并定义这些方法:

public static IEnumerable<Person> OrderByName(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByAge(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByHeight(this IEnumerable<Person> people);
public static IEnumerable<Person> OrderByWeight(this IEnumerable<Person> people);

这会完全糟透了。我的意思是,首先,代码的可重用性变得无限低,因为它只适用于 Person 的集合。类型。此外,我们需要将完全相同的代码复制并粘贴四次,每次只更改 1 或 2 行(其中引用了 Person 的相关属性——否则它们看起来都一样)!这很快就会变得一团糟,无法维护。

因此,委托(delegate)允许您通过抽象出代码中可以切换进出的某些行为,使您的代码更可重用可维护。

关于c# - 委托(delegate)们,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567478/

相关文章:

c# - 如何在 Winform DataGridView 中创建不同的单元格格式

c# - 将所有首字母转换为大写,每个单词的首字母小写

c# - 如何提交包含带有输入元素的多页表格的表单

c# - 通过匿名委托(delegate)取消订阅事件

ios - 从应用程序委托(delegate)访问全局变量

c# - 测试委托(delegate)是否平等

c# - 使用 C# 代码或 .net 以编程方式在 windows azure 中创建虚拟机

c# - 在 linqtoSQL 中使用主键

python-3.x - 如何使用 Python 和 ask-sdk( intent 链接)将 intent 委托(delegate)给 Alexa?

C# 使用 lambda 表达式委托(delegate)逆变