什么是委托? [英] What is Delegate?
问题描述
我很困惑代表的实际角色是什么?
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?
推荐答案
我喜欢将委托视为指向函数的指针".这可以追溯到 C 天,但这个想法仍然成立.
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.
这是参考C#你可以看看:
例如,在 C# 中,假设我们有一个我们想做的计算,我们想使用一种不同的计算方法,直到运行时我们才知道.所以我们可能有几个这样的计算方法:
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);
}
我们可以调用 CalcMyTotal
方法,传入我们想要使用的委托方法.
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屋!