如何理解C#代表? [英] How to understand C# delegates?
本文介绍了如何理解C#代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下示例:
Consider the example below:
private void button1_Click(object sender, EventArgs e)
{
DelegateSample obj = new DelegateSample();
DelFunc delobj1 = new DelFunc(obj.func1);
delobj1 += new DelFunc(obj.func2);
delobj1 += new DelFunc(obj.func3);
obj.functionAll(delobj1);
}
}
class DelegateSample
{
public void func1()
{
MessageBox.Show("You just called func1");
}
public void func2()
{
MessageBox.Show("You just called func2");
}
public void func3()
{
MessageBox.Show("You just called func3");
}
public void functionAll(Delegate o)
{
Delegate[] objdel= o.GetInvocationList();
for (int i = 0; i < objdel.Length; i++)
{
DelFunc obj = (DelFunc)objdel[i];
obj.Invoke();
}
}
在这里,我有一个引用3个方法的委托对象.我添加了方法引用,并且将委托对象作为参数传递给方法.单击按钮时调用此方法,因此我想知道如何当我已经在编译时添加了所有3个方法的引用时,将在运行时"期间调用这些方法.
Here i have a delegate object which references 3 methods.I have added the method references and the delegate object is being passed as an argument to a method.This method is called when the buttom is clicked.Hence I''d like to know how these methods are called during "RUNTIME" when I have already added the references of all the 3 methods in the compile time.
推荐答案
好,您的代码很复杂.你为什么要这样?您想知道什么?您的代码有效吗,您想知道它如何起作用?该方法之所以被称为是因为您已经获得了对它们的引用,所以它知道要调用什么.
Well, your code is convoluted. Why are you dong this ? What is it you want to know ? Does your code work and you want to know HOW it works ? The methods get called BECAUSE you''ve got references to them, so it knows what to call.
C#-委托101-实际示例 [ ^ ]
http://msdn.microsoft.com/en-us/library/aa288459%28v = vs.71%29.aspx [ ^ ]
http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in- C.aspx [ ^ ]
以上链接可以帮助您理解.
C# - Delegates 101 - A Practical Example[^]
http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx[^]
http://www.dotnetscraps.com/dotnetscraps/post/Explaining-Delegates-in-C.aspx[^]
Above links may help you to understand.
您需要阅读有关C#委托的内容,请从以下链接开始:
了解C#中的代理 [ http://www.c-sharpcorner.com/UploadFile/Ashush/Delegates02152008155757PM/Delegates.aspx [ ^ ]
http://msdn.microsoft.com/en-us/library/aa288459%28v = vs.71%29.aspx [ ^ ]
C尖代表 [
You need to read stuffs on C# delegates, start with these links:
Understanding Delegates in C#[^]
http://www.c-sharpcorner.com/UploadFile/Ashush/Delegates02152008155757PM/Delegates.aspx[^]
http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx[^]
C-sharp Delegates[^]
hope it helps :)
这篇关于如何理解C#代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文