简体   繁体   中英

C# public list of objects

I'm converting from VB to C# and struggling to workout how to access a public list of objects...

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

    }
}

In my Main module I can't access "myListOfPlayers".

By design you cannot access a non static member from a static member

From 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.

You need static modifier here

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

You need an instance of your Program class:

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

        foreach(var player in p.myListOfPlayers)
        {

        }
    } 

This is the equivalent of:

Dim p As New Program 

Alternatively you could make myListOfPlayers static.

As an additional comment, you should try and follow proper naming conventions, for example: C# classes should have their first letter capitalized. players should be Players .

You cannot access a non-static context from a static context. So try to access the list within your constructor.

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

    }
}

The variable myListOfPlayer is not static so it only exists within the context of an instance of the class. Since the main method is static, it does not exist in the context of an instance, and so it cannot "see" instance members

You need to make you myListOfPlayer static so that you can access it from a instance method.

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

}

try the above code, it should work. let me know if you any question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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