문제

Fields are variables within a class or struct, local variables sit within a method and global variables are accessible in every scope (class and method included).

This makes me think that fields might be global variables but that global variables are not necessarily fields although I cannot think of a variable sitting outside of a class.

Is there a clear difference between the two?

도움이 되었습니까?

해결책

You tagged this C# and C# does not really have 'global variables'.

But a public static field (or property) would come close. The static makes it singular and gives it a 'global' lifetime.

다른 팁

I think Wikipedia's definition is appropriate here:

In object-oriented programming, field (also called data member or member variable) is the data encapsulated within a class or object. In the case of a regular field (also called instance variable), for each instance of the object there is an instance variable: for example, an Employee class has a Name field and there is one distinct name per employee. A static field (also called class variable) is one variable, which is shared by all instances.

So a global variable is pretty much a static field (and therefore, a field).

Global variables are variables that is accessed in the entire scope as you say, usually this is done with static classes. Example code:

public class Demo {
    public static string ThisIsGlobal = "Global";
    private string _field = "this is a field in the class";
    public void DoSomething()
    {
        string localVariable = "Local";
        string localVariable2 = ThisIsGlobal; // VALID
    }

    public static void GlobalMethod()
    {
        string localVariable = _field; // THIS IS NOT VALID!
    }
}

Many people say that global variables and state are bad, I don't think so as long as you use it as it should be used. In the above example the ThisIsGlobal is a global variable because it have the static keyword. As you see in the example you can access static variables from instance methods, but not instance variables from static methods.

Lots of variables sit outside of a particular instance of a class but they are all still contained within "some" class. Basically a global variable sits nearer the top of the object graph high in the sky where it can be seen/referenced by all the later/ lower classes/members in the object graph.

But a global variable is still just a field of some class/module.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top