简体   繁体   中英

Is there an equivalent to static of C in C#?

In CI can do

void foo() {
  static int c = 0;
  printf("%d,", c);
  c ++;
}

foo(); 
foo(); 
foo();
foo();

it should print 0,1,2,3

Is there an equivalent in C#?

Something like:

class C
{
    private static int c = 0;
    public void foo()
    {
        Console.WriteLine(c);
        c++;
    }
}

没有办法实现与静态c函数变量相同的行为......

While some have suggested as static member variable, this is not the same due to visibility. As an alternative to the answer by aquinas, if closures are accepted , then this can be done:

(Note that Foo is aa property and not a method and that c is "per instance".)

class F {
    public readonly Action Foo;
    public F () {
        int c = 0; // closured
        Foo = () => {
            Console.WriteLine(c);
            c++;
        };
    }
}

var f = new F();
f.Foo();  // 0
f.Foo();  // 1

However, C# has no direct equivalent to a static variable in C.

Happy coding.

There are no globals in C#, however, you can create a static field within your class.

public class Foo{
    private static int c = 0;
    void Bar(){
       Console.WriteLine(c++);
    }
}

You can't do it at a method level. The closest you can do at a method level is something like this, and this isn't really that close. In particular, it only works if you have a reference to the enumerator. If someone else calls this method, they won't see your changes.

   class Program {
        static IEnumerable<int> Foo() {
            int c = 0;
            while (true) {
                c++;
                yield return c;
            }
        }
        static void Main(string[] args) {
            var x = Foo().GetEnumerator();
            Console.WriteLine(x.Current); //0            
            x.MoveNext();
            Console.WriteLine(x.Current); //1
            x.MoveNext();
            Console.WriteLine(x.Current); //2
            Console.ReadLine();
        }
    }

What interesting is that VB.NET does support static local variables: http://weblogs.asp.net/psteele/pages/7717.aspx . As this page notes, .NET itself doesn't support this, but the VB.NET compiler fakes it by adding a static class level variable.

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