当前上下文中不存在名称“..." [英] The name '...' does not exist in the current context

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

问题描述

我的 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>();

...

或者,您可以将列表发送到您的 add 方法中.

Alternately you can send the list into your add method.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆