名称“ ...”在当前上下文中不存在

Ari*_*Ari 2 c# methods list public

我有一个列表Main(),我正尝试从一个变量中向该列表添加一个项目。但这会引发错误“当前上下文中不存在名称'dogList'”

在我的addDog()方法内部,dogList.Add()由于上述原因无法正常工作。

namespace DoggyDatabase
{
    public class Program
    {
          public static void Main(string[] args)
        {
        // create the list using the Dog class
        List<Dog> dogList = new List<Dog>();

        // Get user input
        Console.WriteLine("Dogs Name:");
        string inputName = Console.ReadLine();
        Console.WriteLine("Dogs Age:");
        int inputAge = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Dogs Sex:");
        string inputSex = Console.ReadLine();
        Console.WriteLine("Dogs Breed:");
        string inputBreed = Console.ReadLine();
        Console.WriteLine("Dogs Colour:");
        string inputColour = Console.ReadLine();
        Console.WriteLine("Dogs Weight:");
        int inputWeight = Convert.ToInt32(Console.ReadLine());

        // add input to the list.
        addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight);          
    }

    public static void addDog(string name, int age, string sex, string breed, string colour, int weight)
    {
        // The name 'dogList' does not exist in the current context
       dogList.Add(new Dog()
        {
            name = name,
            age = age,
            sex = sex,
            breed = breed,
            colour = colour,
            weight = weight
        });           
    }
}

public class Dog
{
    public string name { get; set; }
    public int age { get; set; }
    public string sex { get; set; }
    public string breed { get; set; }
    public string colour { get; set; }
    public int weight { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

}

Bau*_*uss 5

dogList对于该方法而言是本地的Main。相反,您想要做的是放置dogList在该范围之外。

public class Program
{
    static List<Dog> dogList = new List<Dog>();

...
Run Code Online (Sandbox Code Playgroud)

或者,您可以将列表发送到添加方法中。