本文介绍了名称"..."在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list within my Main() and I'm trying to add an item to that list from within a variable. But it's throwing the error "The name 'dogList' does not exist in the current context"

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

Inside my addDog() method, dogList.Add() is not working due to above.

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

}

推荐答案

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

dogList is local to the method Main. What you want to do instead is to place dogList outside of that scope.

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

...

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

Alternately you can send the list into your add method.

这篇关于名称"..."在当前上下文中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 04:10