代表们,为什么?

Delegates, Why?(代表们,为什么?)

本文介绍了代表们,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
什么时候在 C# 中使用委托?
代表的目的

我看到很多关于使用代表的问题.我仍然不清楚你会在哪里以及为什么要使用委托而不是直接调用方法.

I have seen many question regarding the use of delegates. I am still not clear where and WHY would you use delegates instead of calling the method directly.

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

I have heard this phrase many times: "The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked."

我不明白那个说法是正确的.

I don't understand how that statement is correct.

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

I've written the following examples. Let's say you have 3 methods with same parameters:

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

现在我声明一个委托:

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

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

Now I can take it a step further a declare a handler to use this delegate (or your delegate directly)

调用委托:

MyClass f = new MyClass();

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

或使用处理程序调用

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

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

In these both cases, I see my "multiply" method being specified. Why do people use the phrase "change functionality at runtime" or the one above?

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

Why are delegates used if every time I declare a delegate, it needs a method to point to? and if it needs a method to point to, why not just call that method directly? It seems to me that I have to write more code to use delegates than just to use the functions directly.

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

Can someone please give me a real world situation? I am totally confused.

推荐答案

在运行时改变功能并不是委托完成的.

Changing functionality at runtime is not what delegates accomplish.

基本上,委托可以为您省去大量打字的麻烦.

Basically, delegates save you a crapload of typing.

例如:

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 委托的 lambda 表达式(其中 Tstringintdoubledouble).

In the above code, the p => p.Name, p => p.Age, etc. are all lambda expressions that evaluate to Func<Person, T> delegates (where T is string, int, double, and double, respectively).

现在让我们考虑一下如何在没有委托的情况下实现上述.与其让 OrderBy 方法接受委托参数,不如放弃通用性并定义这些方法:

Now let's consider how we could've achieved the above without delegates. Instead of having the OrderBy method take a delegate parameter, we would have to forsake genericity and define these methods:

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 的相关属性——否则看起来都一样)!这很快就会变成一团无法维护的混乱.

This would totally suck. I mean, firstly, the code has become infinitely less reusable as it only applies to collections of the Person type. Additionally, we need to copy and paste the very same code four times, changing only 1 or 2 lines in each copy (where the relevant property of Person is referenced -- otherwise it would all look the same)! This would quickly become an unmaintainable mess.

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

So delegates allow you to make your code more reusable and more maintainable by abstracting away certain behaviors within code that can be switched in and out.

这篇关于代表们,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:代表们,为什么?

基础教程推荐