简体   繁体   中英

How do I avoid re-initializing a class that never changes?

I have a class that only needs to be initialized once in my code, but the function it is in is called multiple times and the class is initialized again and again. This class only needs to be called once because the data that is passed into it never changes and it is a waste to have my code reinitialize it more than once. I want to have a way for my code to check that this class has already been initialized and can grab the needed information that was already generated. My first thought was to design in the way of the Singleton Pattern, but I don't think that's necessary since this class is not needed anywhere else in my code. What is a simple way of doing something like this?

Make it static. Class will be initialized on first use...

A static class is one approach.

public static class MyClass
{
   public static bool IsInited { get; private set; }
   public static void Init(...)
   {
      ...
      IsInited = true;
   }
}

If the Init has no arguments, eg can set all the properties itself, then you can use a static constructor instead of Init . Basically the constructor will be called the first time that other code accesses a property.

public static class MyClass
{
   public static bool IsUnix { get; private set; }
   static MyClass()
   {
      IsUnix = Environment.NewLine == '\n';
   }

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