[英]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.. 受JavaScript封闭的启发,我尝试使用Func <> Delegate在C#中模拟局部静态变量。这是我的代码。
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#? 我很想知道在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;
然后,不用调用
PrintNextNumber()
,而是执行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
如果您想实际从方法中返回某些东西,则变得更加麻烦,但有可能-您可以
yield return
,然后在调用MoveNext
之后使用Current
检索它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.