samedi 30 mai 2015

How to instantiate unique delegates using an anonymous method in a loop?

Code:

using System.IO;
using System;
using System.Reflection;
using System.Collections.Generic;

class AnyClass
{
    delegate void Del(string str);
    static void Main()
    {
        List<Del> listDel = new List<Del>();

        listDel.Add(delegate(string str) { });
        Console.WriteLine( listDel[0].Method.ToString() );

        listDel.Add(delegate(string str) { });
        Console.WriteLine( listDel[1].Method.ToString() );

        for (int i = 0; i < 2; i++)
        {
            listDel.Add(delegate(string str) { });
            Console.WriteLine( listDel[2+i].Method.ToString() );
        }
    }
}

Output:

Void m__0(System.String)
Void m__1(System.String)
Void m__2(System.String)
Void m__2(System.String)

Why do the delegates instantiated in the loop "point" to the same method (m__2) whereas the ones instantiated outside the loop point to two different methods (m__0 and m__1)?

Is there any way how to instantiate delegates that point to different methods inside a loop?

Example of usage: I need to have delegates as keys in a dictionary, so they need to be unique. Instantiation inside a loop is necessary to provide enough of flexibility.





Aucun commentaire:

Enregistrer un commentaire