简体   繁体   中英

Why am I getting an object reference error on my List<> object?

I have a class called StartingUserInterface that has a list of Teams that is written out as so:

public class StartingUserInterface
{
    public List<Team> Teams = new List<Team>();
    public static string PlayerName;
    AddPlayer();
}

In a method within the same class, I am trying to add a user-specified player name to a user-specified team by first finding the team within the Teams list , and then setting the name of the player to that team:

public static void AddPlayer()
{ 
    PlayerName = Console.ReadLine();
    Team team = new Team();
    team.Name = Console.ReadLine();
    team = Teams.Find(x => x.Name == team.Name);
    team.AddPlayer(PlayerName);
}

Here is a snippet of the Team class:

public class Team
{ 
    public string Name;

    public void AddPlayer(string name)
    {
        Player Player = new Player()
        {
            Name = name;
        };
}

The error message I am getting says

"An object reference is required for the non-static field, method, or property 'StartingUserInterface.Teams'

...when I try to set the Teams list item to the team object: team = Teams.Find(x => x.Name == team.Name); in the AddPlayer() method. Am I doing something obviously wrong? It seems to me that it is saying the List object doesn't exist, but I created an instance of it at the start of the class.

you cannot use a non static field in a static method so you should make Teams List a static variable.

Yours

public List<Team> Teams = new List<Team>();

Changed

public static List<Team> Teams = new List<Team>();

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