[英]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(). 因此,我有一个静态类,其中的一个列表声明为它的成员之一,并且我在一个函数中填充该列表,可以说它称为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) 1)调用它作为参数2)在构造函数中实例化它(尝试使类保持静态。我正在使用模板,因此我无法真正更改类的结构)
Without somehow instantiating though, I will obviously receive null exceptions, so I was wondering if there is a 3rd way to do this. 但是,如果不进行任何实例化,我显然会收到null异常,因此我想知道是否存在第三种方法。
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
,但可以确保始终定义该列表:
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: 另一种选择是向列表的每种用法添加一个null
检查:
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. 我会调用一个名为“ Initialize”的函数,该函数是静态的,并会照顾您的静态成员。
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: 从外部调用您的Initialize-Function:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.