Вот код, над которым я работал:
Код: Выделить всё
namespace GenericList
{
class Program
{
static void Main(string[] args)
{
// I understand the basics of object instantiation,
// but I'm seeking clarification on how objects are added to a List.
List facts = new List();
// Although I pass arguments to the constructor of each Cities object,
// I'm unsure about the underlying process when adding these objects to the List.
facts.Add(new CityFact(1, "Durban - Home to the largest harbor in Africa"));
facts.Add(new CityFact(2, "Johannesburg - The largest city in the country"));
facts.Add(new CityFact(3, "Gqebetha - Also known as P.E, the friendly city"));
facts.Add(new CityFact(4, "Bloemfontien - Host of the Rose Festival"));
facts.Add(new CityFact(5, "Pretoria - South Africa's capital"));
Console.WriteLine("Which city would you like to know an interesting fact for?" +
"\n1) Durban" +
"\n2) Johannesburg" +
"\n3) Gqebetha" +
"\n4) Bloemfontien" +
"\n5) Pretoria" +
"\nEnter the number for the city you want:");
int answer = int.Parse(Console.ReadLine());
bool found = false;
for (int i = 0; i < facts.Count; i++)
{
// I understand basic looping structures, but I'm unclear about
// how the List elements are accessed and compared here.
if (facts[i].Id.Equals(answer))
{
Console.WriteLine("\nANSWER: " + facts[i].Fact);
found = true;
}
}
if (!found)
{
Console.WriteLine("\nWe couldn't find what you are looking for.");
}
}
}
class CityFact
{
int id;
string fact;
public CityFact(int id, string fact)
{
this.id = id;
this.fact = fact;
}
public int Id { get => id; set => id = value; }
public string Fact { get => fact; set => fact = value; }
}
}
- Процесса добавления объектов в список и как они хранятся внутри.
- Доступ к элементам списка и их сравнение с помощью цикла.
- Любая дополнительная ясность в отношении объекта создание экземпляров и использование конструкторов.
Подробнее здесь: https://stackoverflow.com/questions/724 ... in-c-sharp
Мобильная версия