【问题标题】:Using a list from another method in a static class使用静态类中另一个方法的列表
【发布时间】:2013-07-14 21:53:28
【问题描述】:

所以我有一个静态类,其中一个列表声明为它的成员之一,我将列表填充到一个函数中,假设它称为 PopulateList()。是否可以在另一个函数中修改列表而无需:

1) 将其作为参数调用 2)在构造函数中实例化它(试图保持类静态。我正在使用模板,所以我不能真正改变类的结构)

如果不以某种方式实例化,我显然会收到空异常,所以我想知道是否有第三种方法可以做到这一点。

       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
          }
       }

【问题讨论】:

  • 代码会比只有文字好一点,能不能加点代码?
  • 请显示一些代码。不清楚为什么不能直接初始化成员。
  • 为什么不在运行函数时检查列表是否已实例化,如果尚未实例化则实例化它?

标签: c# list nullreferenceexception


【解决方案1】:

您可以使用static constructor 或静态初始化。它将允许您保留您的课程static,但将确保始终定义列表:

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

    // etc
}

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

另一种选择是在列表的每次使用中添加null 检查:

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

【讨论】:

  • 我仍然在使用静态构造函数时遇到了一些问题。它说列表是一个字段,但用作类型。我还在类结构或接口中得到一个无效的“{”
  • @user1819301 我错过了第一个示例中的一些括号。
  • 感谢 RoadieRich。这就是我一直在寻找的答案。
【解决方案2】:

我会调用一个名为“Initialize”的函数,它是静态的,负责处理您的静态成员。

如果可能的话,我建议不要使用静态成员。

为什么?

代码 sn-p

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?");
    }
}

从外部调用您的 Initialize-Function:

 YourClass.InitializeList();

编辑:给定您的代码,您也可以这样做:

  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
          }
       }

【讨论】:

  • 我不同意第 2 点 They use memory even though you don't use the class (they live as long the project lives) 这是错误的,除非您至少使用它 Once
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多