Hallo!

Hier mal ein Beispiel dafür wie lokaler Zustand bei der Erzeugung einer anonymen Methode (delegate(...){...}) erhalten bleibt:
Code csharp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Text;
 
namespace De.Tutorials.Training
{
    public class LocalDelegateStateExample
    {
        public delegate void Operation();
 
        public static void Main(string[] args)
        {
            foreach (Operation operation in CreateOperations())
            {
                operation();
            }
 //Edit über ein MulticastDelegate kann man übrigens die ganzen Aktionen auf einen Schlag laufen lassen:
            Console.WriteLine("Multicast Delegate: ");
 
            Operation o = (Operation)Delegate.Combine(CreateOperations());
            o();
 
        }
 
        public static Operation[] CreateOperations()
        {
            Operation[] operations = new Operation[10];
 
            for (int i = 0; i < operations.Length; i++)
            {
                int j = i;
                operations[i] = delegate()
                {
                    Console.WriteLine(j);
                };
            }
            return operations;
        }
    }
}

In Java schaut das dann so aus:
Code java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * 
 */
package de.tutorials;
 
/**
 * @author Tom
 *
 */
public class PreserveLocalStateExample {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        for(Runnable runnable : createRunnables()){
            runnable.run();
        }
    }
 
    private static Runnable[] createRunnables() {
        Runnable[] runnables = new Runnable[10];
        
        for(int i = 0; i < runnables.length;i++){
            final int j = i;
            runnables[i] = new Runnable(){
                public void run() {
                    System.out.println(j);
                }
            };
        }
        
        return runnables;
    }
}

Ausgabe:
Code :
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9

Gruß Tom