繁体   English   中英

C#公共对象列表

[英]C# public list of objects

我正在从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”。

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

从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>();

您需要一个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

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

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

    }
}

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

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

public static List<players> myListOfPlayers = new List<players>();
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; }

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM