C#公共对象列表

时间:2014-03-11 08:56:12

标签: c# .net list static instance

我正在从VB转换为C#并努力研究如何访问公共对象列表......

class Program
{
    public List<players> myListOfPlayers = new List<players>();

    static void Main(string[] args)
    {

        foreach(var player in myListOfPlayers)
        {

        }
    } 

    class players
    {
        public string playerName { get; set; }
        public string playerCountry { get; set; }

    }
}

在我的主模块中,我无法访问“myListOfPlayers”。

5 个答案:

答案 0 :(得分:4)

按照设计,您无法从静态成员

访问非静态成员

来自MSDN Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

这里需要静态修饰符

public static List<players> myListOfPlayers = new List<players>();

答案 1 :(得分:4)

您需要Program班级的实例:

  static void Main(string[] args)
    {
        Program p = new Program(); // p is the instance.

        foreach(var player in p.myListOfPlayers)
        {

        }
    } 

这相当于:

Dim p As New Program 

或者,您可以myListOfPlayers静态。

作为附加注释,您应该尝试遵循正确的命名约定,例如:C#类的首字母应该大写。 players应为Players

答案 2 :(得分:0)

您无法从静态上下文访问非静态上下文。因此,请尝试访问构造函数中的列表。

class Program
{
    public List<players> myListOfPlayers = new List<players>();

    public Program(){
      foreach(var player in myListOfPlayers)
      {

      }
    } 

static void Main(string[] args)
{
    new Program();

} 

    class players
    {
        public string playerName { get; set; }
        public string playerCountry { get; set; }

    }
}

答案 3 :(得分:0)

变量myListOfPlayer不是静态的,因此它只存在于类的实例的上下文中。由于main方法是静态的,因此它不存在于实例的上下文中,因此它不能“看到”实例成员

您需要使myListOfPlayer静态,以便您可以从实例方法访问它。

public static List<players> myListOfPlayers = new List<players>();

答案 4 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        List<players> myListOfPlayers = new List<players>();

        foreach (var player in myListOfPlayers)
        {

        }
    }


}
class players
{
    public string playerName { get; set; }
    public string playerCountry { get; set; }

}

尝试上面的代码,它应该工作。 如果您有任何问题,请告诉我