什么是代表? [英] What is Delegate?

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

问题描述

我很困惑,代表的实际角色是什么?我在采访中多次被问到这个问题,但是我不认为面试官对我的答案感到满意。



任何人都可以告诉我最好的定义一个句子,有一个实际的例子?



谢谢

解决方案

喜欢把一个委托人称为一个指向一个函数的指针。这可以追溯到C天,但是这个想法依然存在。



这个想法是,您需要能够调用一段代码,但您将要调用的代码段在运行时才是不知道的。所以你为此而使用委托。代表们可以派上用场的事件处理程序,例如,根据不同的事件进行不同的处理。



以下是您可以查看的C#的参考:



在C#中,例如,假设我们有一个我们想做的计算,我们想使用一个不同的计算方法,直到运行时才会知道。所以我们可能会有一些这样的计算方法:

  public static double CalcTotalMethod1(double amt)
{
return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
return amt * .056 + 42.43;
}

我们可以这样声明一个委托签名:

  public delegate double calcTotalDelegate(double amt); 

然后我们可以声明一个方法,该方法将委托作为参数,如下所示:

  public static double CalcMyTotal(double amt,calcTotalDelegate calcTotal)
{
return calcTotal(amt);
}

我们可以调用 CalcMyTotal 方法传递给我们想要使用的委托方法。

  double tot1 = CalcMyTotal(100.34,CalcTotalMethod1); 
double tot2 = CalcMyTotal(100.34,CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);


I am confused that what is the actual role of a delegate? I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.

Can anyone tell me the best definition, in one sentence, with a practical example ?

Thanks

解决方案

I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.

The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.

Here's a reference for C# you can look at:

In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:

public static double CalcTotalMethod1(double amt)
{
    return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
    return amt * .056 + 42.43;
}

We could declare a delegate signature like this:

public delegate double calcTotalDelegate(double amt);

And then we could declare a method which takes the delegate as a parameter like this:

public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
    return calcTotal(amt);
}

And we could call the CalcMyTotal method passing in the delegate method we wanted to use.

double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆