C#中的委托数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/255098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:09:17  来源:igfitidea点击:

Delegate Array in C#

c#arraysdelegates

提问by pro3carp3

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

EDIT: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).

编辑:数组的原因是我需要根据需要通过索引调用委托函数。它们不是为了响应事件而运行的。我在我的代码中看到一个严重的(愚蠢的)错误,因为我试图使用 pd[] 类型而不是数组的名称(委托)来执行委托函数。

采纳答案by Jon Skeet

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();

回答by Romain Verdier

public class MainClass
{
    static void Main()
    {
        pd[0]();
        pd[1]();
    }
}

回答by Charles Bretana

In .Net, any delegate is in fact actually a "multicast" delegate (it inherits from this built-in base class), and therefore contains an internal linked list which can contain any number of target delegates.

在 .Net 中,任何委托实际上都是一个“多播”委托(它继承自这个内置基类),因此包含一个内部链表,该链表可以包含任意数量的目标委托。

You can access this list by calling the method GetInvocationList() on the delegate itself. This method returns an array of Delegates...

您可以通过调用委托本身的 GetInvocationList() 方法来访问此列表。此方法返回一个委托数组...

The only restriction is that all the delegates inside of a given delegate's linked list must have the same signature, (be of the same delegate type). If you need your collection to be able to contain delegates of disparate types, then you need to construct your own list or collection class.

唯一的限制是给定委托的链表中的所有委托必须具有相同的签名(具有相同的委托类型)。如果您需要您的集合能够包含不同类型的委托,那么您需要构建您自己的列表或集合类。

But if this is ok, then you can "call" the delegates in a given delegate's invocation list like this:

但是如果没问题,那么您可以像这样“调用”给定委托的调用列表中的委托:

public delegate void MessageArrivedHandler(MessageBase msg);
public class MyClass
{
     public event MessageArrivedHandler MessageArrivedClientHandler;   

     public void CallEachDelegate(MessageBase msg)
     {
          if (MessageArrivedClientHandler == null)
              return;
          Delegate[] clientList = MessageArrivedClientHandler.GetInvocationList();
          foreach (Delegate d in clientList)
          {
              if (d is MessageArrivedHandler)
                  (d as MessageArrivedHandler)(msg);
          }
     }
}

回答by Garric

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        pd[0]();
        pd[1]();
    }

    public delegate void delegates();

    static delegates[] pd = new delegates[] 
                            { 
                               new delegates(MyClass.p1), 
                               new delegates(MyClass.p2) 
                            };

    public static class MyClass
    {
        public static void p1()
        {
            MessageBox.Show("1");
        }

        public static void p2()
        {
            MessageBox.Show("2");
        }
    }
}

回答by Garric

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        pd[0](1);
        pd[1](2);
    }

    public delegate void delegates(int par);
    static delegates[] pd = new delegates[] 
                                     { 
                                      new delegates(MyClass.p1), 
                                      new delegates(MyClass.p2) 
                                     };
    public static class MyClass
    {

        public static void p1(int par)
        {
            MessageBox.Show(par.ToString());
        }

        public static void p2(int par)
        {
            MessageBox.Show(par.ToString());
        }


    }

}