简体   繁体   中英

C# What is the difference between creating a static object outside a class VS creating it inside a class?

I want to understand the difference between 3 sets of snippets below:

private static FirstObject o = new FirstObject();
public class ClassA
{
}

//-----------------------------------------------------

public class ClassA
{
    private static FirstObject o = new FirstObject();
}

//-----------------------------------------------------

public class ClassA
{
    private static FirstObject o;

    public ClassA
    { 
        o = new FirstObject();
    }
}

Please help me understand in terms of scope, memory, performance and usage of these.

Thank you.

  1. Invalid, as you can't have a variable outside of object

  2. The proper way - the class has a static member, which is initialized when the class is accessed for the first time

  3. Very bad, because every time when new object is created the static object will be recreated.

The first option will not compile. A static variable in C# must be scoped to a class or struct.

The second option is the preferred mechanism.

The third option is wrong because this creates a new FirstObject each time an instance of ClassA is created, which is almost certainly not what you want.

A fourth option would be to leverage a static constructor, eg,

public class ClassA
{
    private static FirstObject o;
    static ClassA
    {
        o = new FirstObject();
    }
}

This option is useful if there is some special construction constraints for FirstObject . In this example, though, choose option 2 over option 4. Just know that option 4 exists.

Three cases below...

  1. Assuming a typo here missing some outer construct... "o" is declared so that it will be globally accessible, as a single object, to the entire application. It will have one common set of all properties and data. It can be access directly by "Namespace.o"
  2. "o" is declared so that it will be globally accessible, as a single object, to the entire application, However it is only accessible through another defined instance of "ClassA". Each separate instance of ClassA will have the same, single "o" object with the same properties and data.
  3. This doesn't look right to me, I'm assuming "ol" is supposed to "o;". Even with this the code looks like its missing something. if the Line "o = new FirstObject" is correct it is not accessible in this fashion.

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