anonymous delegates in .net 2.0
This is a real quick sample of how anonymous delegates work in .Net 2.0.
your simple code:delegate void test ();
public static void Main()
{
test r = null;
for ( int i = 1; i < 11; ++i )
{
int p = i;
test x = r;
r = delegate { Console.WriteLine ("{0}", p ); if(x != null) x(); };
}
r();
Console.ReadLine ();
}
gets translated to:class tmpClass
{
test x;
int p;
public void Execute ()
{
Console.WriteLine ("{0}", p );
if(x != null)
x();
}
}
delegate void test ();
public static void Main()
{
test r = null;
for ( int i = 1; i < 11; ++i )
{
tmpClass tmp = new tmpClass();
tmp.x = r;
tmp.p = i;
r = new test(tmp.Execute);
}
r();
Console.ReadLine();
}
So, for this simple (contrived) example, you end up creating 10 temporary objects.
I really like the idea of anonymous delegates, but their use needs to be reviewed carefully.
No comments:
Post a Comment