无法创建静态类的实例' diamondmine.MyObject'

时间:2015-05-28 06:29:13

标签: c#

尝试创建ArrayList并用对象填充它,但是遇到了这个错误:

  

无法创建静态类的实例' diamondmine.MyObject'

到目前为止的代码:

public static class MySettings
{
  //some lines
  public static ArrayList myObjects { get; set; }

  static MySettings()
  {
    //some lines
    myObjects = new ArrayList();
  }
}

public static class MyObject
{
  public static int a { get; set; }
  public static int b { get; set; }

  static MyObject()
  {
    a = 1;
    b = 2;
  }
}

这就是我尝试添加新对象的方式:

//some code
MySettings.myObjecs.Add(new MyObject());
//more code

Rly不知道问题所在,我正在做MSDN编写的事情:(

2 个答案:

答案 0 :(得分:5)

如错误所示,您无法创建静态类的实例。

您的MyObject类不应该是静态的,这样可以创建它的实例。

有关静态和非静态的更多信息,请参阅此处:Static vs non-static class members

要回答评论中的问题,您的代码最终将会是这样的:

public static class MySettings
{
  //some lines
  public List<MyObject> myObjects { get; set; }

  static MySettings()
  {
    //some lines
    myObjects = new List<MyObject>();
  }
}

public class MyObject
{
  public int a { get; set; }
  public int b { get; set; }

  public MyObject()
  {
    a = 1;
    b = 2;
  }
}

然后用法是:

MySettings.myObjects.Add(new MyObject());
MySettings.myObjects[0].a; // returns 1

答案 1 :(得分:1)

用这样的方式替换你的代码:

public static class MySettings
{
  //some lines
  public static ArrayList MyObjects { get; private set; }

  static MySettings()
  {
    //some lines
    MyObjects = new ArrayList();
  }
}

public class MyObject
{
  public int a { get; set; }
  public int b { get; set; }

  public MyObject()
  {
    a = 1;
    b = 2;
  }
}

请注意,MyObjectsprivate set