简体   繁体   中英

Declaring a static object from inside its own class

Hi I have some code where I use a static object of Manager to call methods from Manager:

public class Manager
{
    public static Manager sManager = new Manager();
    public int x;

    public Manager()
    {  
    }


    public void Modify()
    {
        x ++;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Manager.sManager.x);
        Manager.sManager.Modify();
        Console.WriteLine(Manager.sManager.x);
        Console.ReadLine();
    }
}

Is this a good way of accessing a method from Manager from outside or is there a better way if the class Manager must own the method Modify.

Would use of events in this case be a better way to build this and have Manager listen for an update?

Or is there a better way to handle this even if I want the method Modify to stay inside the Manager class?

It depends on the architecture you're trying to build.

Make everything static

If it's as simple as that, just make x and Modify static and you won't need an instance.

Use a singleton pattern

If you do need a Manager instance your code would be better using a Singleton pattern

private static Manager _manager;

public static Manager Manager
{
   get 
   {
      if (_manager == null)
      {
         _manager = new Manager();
      }
      return instance;
   }
}

There is no reason here to create a static field of same type in the Manager class. You just need to create an object and then call the needed methods.

A more better way can be to make field private and just expose it for reading so that it can't be modified directly, and we only modify it by calling the modify() method:

public class Manager
{

  private int x;

  public int X
  {
    get
    {
       return x;
    }
  }

  public Manager()
  {  
  }


  public void Modify()
  {
      x++;
  }
} 

and then in your Program class use it:

class Program
{
    static void Main(string[] args)
    {
        Manager objManager = new  Manager();
        Console.WriteLine(objManager.X);

        objManager.Modify();

        Console.WriteLine(objManager.X);
        Console.ReadLine();
    }
}

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