简体   繁体   中英

Using a list from another method in a static class

So I have a static class with a list declared as one of it's members, and I populate the list in a function lets say it's called PopulateList(). Is it possible to modify the list in another function without:

1) Calling it as a parameter 2) Instantiating it in a constructer (Trying to keep the class static. I'm working off of a template so I can't really change the structure of the classes)

Without somehow instantiating though, I will obviously receive null exceptions, so I was wondering if there is a 3rd way to do this.

       public Static class MyClass{

             static public List<String> m_SuiteFileNameList2=null;


        public static bool Function1(inp){
              //m_SuiteFileNameList2 stuff
         }

        public static void Function2(){
             //m_SuiteFileNameList2 other stuff
          }
       }

You can either use a static constructor , or static initialization. It will allow you to keep your class static , but will ensure that the list is always defined:

static class MyClass
{
    static MyClass()
    {
        MyList = new List<Whatever>();
    }

    // etc
}

or

static class MyClass
{
    public static List<Whatever> MyList = new List<Whatever>();
}

Another option is to add a null check to every usage of the list:

public static void MyMethod()
{
    if (MyList == null)
    {
        MyList = new List<Whatever>();
    }
    //etc
}

I would call a function called 'Initialize' which is static and takes care of your static members.

Though I would recommend against static members if possible.

Why?

code snippet

public static class YourClass
{
    public static List<string> YourList;

    public static void InitializeList()
    {
        YourList = new List<string>();
        YourList.Add("hello");
        YourList.Add("how");
        YourList.Add("are");
        YourList.Add("you?");
    }
}

Call your Initialize-Function from outside:

 YourClass.InitializeList();

EDIT: Given your code , you can also do it this way:

  public Static class MyClass{

             static public List<String> m_SuiteFileNameList2=null;


        public static bool Function1(inp){
             if(m_SuiteFileNameList2 == null)
             { m_SuiteFileNameList2 = new List<String>();}
              //m_SuiteFileNameList2 stuff
         }

        public static void Function2(){
             if(m_SuiteFileNameList2 == null)
             { m_SuiteFileNameList2 = new List<String>();}
             //m_SuiteFileNameList2 other stuff
          }
       }

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