用C#委托数组 [英] Delegate Array in C#
本文介绍了用C#委托数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从委托数组中调用委托函数.我已经能够创建代表数组,但是如何称呼代表?
I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?
public delegate void pd();
public static class MyClass
{
static void p1()
{
//...
}
static void p2 ()
{
//...
}
//...
static pd[] delegates = new pd[] {
new pd( MyClass.p1 ),
new pd( MyClass.p2)
/* ... */
};
}
public class MainClass
{
static void Main()
{
// Call pd[0]
// Call pd[1]
}
}
数组的原因是,我需要根据需要通过索引调用委托函数.它们不会响应事件而运行.我在代码中看到一个严重(愚蠢)错误,因为我尝试使用pd []类型而不是数组名称(代理)执行委托函数.
The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).
推荐答案
如果它们都是同一类型,为什么不将它们组合成一个多播委托呢?
If they're all the same type, why not just combine them into a single multicast delegate?
static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;
...
pd();
这篇关于用C#委托数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文