简体   繁体   中英

Local Static variable in C#?

Inspired by JavaScript Closures I tried to Simulate Local static variables in C# using Func<> Delegate... Here is my code..

public Func<int> Increment()
    {
        int num = 0;
        return new Func<int>(() =>
        {
            return ++num;
        });
    }

Func<int> inc = Increment();
Console.WriteLine(inc());//Prints 1
Console.WriteLine(inc());//Prints 2
Console.WriteLine(inc());//Prints 3

I am eager to know if there is any other way of simulating local static variable in C#? Thank You.

This is absolutely horrible, but one way would be to use an iterator method and discard the output. For example, if you wanted:

public void PrintNextNumber()
{
    static int i = 0; //Can't do this in C#
    Console.Out.WriteLine(i++);
}

You could instead write:

public IEnumerator<object> PrintNextNumber()
{
    int i = 0;
    while (true)
    {
        Console.Out.WriteLine(i++);
        yield return null;
    }
}

Then instead of calling PrintNextNumber() , you'd do var printNext = PrintNextNumber(); printNext.MoveNext; var printNext = PrintNextNumber(); printNext.MoveNext; .

I really only wrote this answer for satisfying curiousity, I absolutely would not recommend really doing this!

It becomes even more nasty if you want to actually return something from the method but it's possible- you can yield return instead, then retrieve it using Current after having called MoveNext

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM