Anonyme Methoden und lokaler Zustand

Thomas Darimont

Erfahrenes Mitglied
Hallo!

Hier mal ein Beispiel dafür wie lokaler Zustand bei der Erzeugung einer anonymen Methode (delegate(...){...}) erhalten bleibt:
C#:
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:
Java:
/**
 * 
 */
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:
0
1
2
3
4
5
6
7
8
9

Gruß Tom
 
Zurück