2017-02-01 10 views
1

У меня есть список в пределах моего 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; } 
} 

}

+0

Если вы хотите использовать одну и ту же переменную DogList в двух или более методах, тогда объявите переменную глобально –

+0

Возможный дубликат http://stackoverflow.com/questions/10270479/the-name-temp-does-not-exist- in-current-context-c-desktop-application –

ответ

0

dogList существует только в рамках метода Main. Если вы объявляете переменную в одном методе, она становится местным и не может быть доступна другим способом.

Вы могли бы решить эту проблему, передавая необходимую переменную в качестве параметра:

public static void addDog(string name, int age, string sex, string breed, string colour, int weight, List<Dog> dogList) 

Теперь вы передаете переменную в вызове, как это:

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

или вы можете объявить переменную на сфера охвата этого класса:

public class Program 
{ 
    // create the list using the Dog class 
    static List<Dog> dogList = new List<Dog>(); 

В последней версии вам необходимо объявить его статичным, ot в свою очередь, компилятор потребует экземпляра класса Program для доступа к переменной

3

dogList является локальным для метода Main. Вместо этого вы хотите разместить dogList вне этой области.

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

... 

Альтернативно вы можете отправить список в свой метод добавления.

+0

Отлично! Я пробовал это раньше, но не добавил «Static», похоже, мне нужно будет сосредоточиться на том, чтобы схватить их. – Ari

0

Переменная dogList локально привязана к основному методу, поэтому она недоступна для другого метода в вашем классе, у вас есть несколько способов сделать это правильно, одним из решений может быть передача dogList, а также параметр для этого метод, как:

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

и изменить подпись addDog метода, а также быть:

public static void addDog(string name, int age, string sex, string breed, string colour, int weight, List <Dog> dogList) 
{ 
} 

Если вы не хотите, чтобы сделать это так, и другое решение может быть, чтобы сделать ваш dogList variab ле на уровне класса т.е. сделать его поле, как:

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

Основная проблема заключается в том, что вы объявили dogList локально в главном. Вы также объявили addDog статическим. Статические методы находятся за пределами текущего объекта.

Подумайте о главном, как о своей гостиной, в которой вы стоите в своей гостиной. Теперь подумайте о addDog как о своей ванной, в которой я стою. Мы знаем, что друг друга существует, поэтому мы не можем общаться.

public class DogDb 
{ 
    // DogDb contains a list of dogs 
    public List<Dog> dogs { get; set; } 

    public DogDb() { 
     dogs = new List<Dog>(); 
    } 
    // DogDb can control adding new dogs to its list of dogs. 
    public void addDog(string name, int age, string sex, string breed, string colour, int weight) 
    {    

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

public class Program 
{ 
     public static void Main(string[] args) 
    { 

    // Create a new instance of our DogDB class. 
    var DogDb = new DogDb(); 

    // 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 object. 
    DogDb.addDog(inputName, inputAge, inputSex, inputBreed, inputColour, inputWeight); 

} 
1

@Ari ....Вот как вы можете это сделать

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication4 
{ 
    namespace DoggyDatabase 
    { 
     public class Program 
     { 
      private static List<Dog> dogList = new List<Dog>(); 

      public static void Main(string[] args) 
      { 
       // create the list using the Dog class     

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

Список было недоступно из-за его защиту level.When вы должны использовать список в другом методе, то вы должны объявить его первым. Счастливое кодирование