c# - 当前上下文中不存在名称 '...'

标签 c# list methods 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; }
}

}

最佳答案

dogList 是方法 Main 的本地。您要做的是将 dogList 放在该范围之外。

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

...

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

关于c# - 当前上下文中不存在名称 '...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974155/

相关文章:

c# - VS2012专业版如何生成UML图?

java - 如何获取List中多个最大值的索引

arrays - 在 Array 上定义一个 trim 方法,删除第一个和最后一个元素

python - 格式化字典键 : AttributeError: 'dict' object has no attribute 'keys()'

c# - 如何在同一URL下托管多个.NET Core应用

c# - 将回调函数传递给另一个类

c# - 如何在 C# 中获取 float 的 IEEE 754 二进制表示

ios - 如何制作从 SwiftUI 列表中删除多行的动画?

python - 匹配列表中的多个单词

C# 方法不遵循顺序