我编写了一个简单的 C# 程序来管理
List
的 CityFact
。虽然代码运行没有错误,但我发现自己很难完全掌握一些概念,特别是关于对象实例化和列表操作。
这是我一直在编写的代码:
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<CityFact> facts = new List<CityFact>();
// 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; }
}
}
我将非常感谢任何关于以下方面的见解或解释:
List
添加对象的过程以及它们在内部的存储方式。List
中的元素。非常感谢您的时间和帮助。
List<Cities> cities = new List<Cities>();
这里创建一个List,其中仅包含Cities类的对象。
Add()
,它将一个新对象附加到列表中(在这种情况下,只有您在第一行中声明的 Cities 对象 List<Cities>
)。cities.Add(new Cities(1, "Durban - Home to the largest harbor in Africa"));
如果我打破这条线,这将是:// Creating a new Cities object
var newCity = new Cities(1, "Durban - Home to the largest harbor in Africa");
cities.Add(newCity );
代码块的最后一行将
newCity
附加到 cities
列表中
希望您现在明白了,如果有任何不清楚的地方请告诉我
我用 linq 重写了,这样你就可以看到一种不同的方法。更容易阅读代码
void Main()
{
List<Cities> cities = new List<Cities>();
//add to cities array a new City class, since constructor accept 2 parameters you supply them on new object creation
Cities city;
city = new Cities(1, "Durban - Home to the largest harbor in Africa");
cities.Add(city);
city = new Cities(2, "Johannesburg - The largest city in the country");
cities.Add(city);
city = new Cities(3, "Gqebetha - Also known as P.E, the friendly city");
cities.Add(city);
city = new Cities(4, "Bloemfontien - Host of the Rose Festival");
cities.Add(city);
city = new Cities(5, "Pretoria - South Africa's capital");
cities.Add(city);
//different approach: create list with objects
cities = new List<Cities>()
{
new Cities(1, "Durban - Home to the largest harbor in Africa"),
new Cities(2, "Johannesburg - The largest city in the country"),
new Cities(3, "Gqebetha - Also known as P.E, the friendly city"),
new Cities(4, "Bloemfontien - Host of the Rose Festival"),
new Cities(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());
var result = cities
.Select((obj, index) => new { index, obj }) //set index for each object
.Where(w => w.index == answer)
.FirstOrDefault();
if (result == null)
Console.WriteLine("\nWe couldn't find what you are looking for.");
else
Console.WriteLine("\nANSWER: " + result.obj.City);
}
class Cities
{
//class properties
public int Id { get; set; }
public string City { get; set; }
//Parameterized Constructor https://www.tutlane.com/tutorial/csharp/csharp-constructors-with-examples#divcspzcst
public Cities(int id, string city)
{
Id = id;
City = city;
}
}
与
List<Cities> cities = new List<Cities>();
您创建了一个新的列表对象,可以存储
Cities
对象。泛型类型参数 <Cities>
表示列表项的类型,并不引用构造函数。例如,以下代码将创建一个可以存储整数值的列表:
List<int> lst = new List<int>();
List<T>
类是泛型类型。无论列表项的类型是什么,添加、删除、枚举等列表的基本操作都是相同的。通过创建泛型类型,您可以在不知道稍后创建对象时使用哪些类型的情况下实现功能。您可以将其与方法进行比较:实现该方法时,您定义参数及其类型;当您调用该方法时,您提供参数的值。
以下行中的代码执行两个任务:
cities.Add(new Cities(1, "Durban - Home to the largest harbor in Africa"));
首先,通过构造函数创建并初始化一个
Cities
类型的新对象。其次,将其添加到列表中。这是两个单独的步骤,也可以这样写:
// Create new object of type Cities
var city = new Cities(1, "Durban - Home to the largest harbor in Africa");
// Add newly created object to list
cities.Add(city);
正如 @BinRohan 在评论中建议的那样,将
Cities
类重命名为 City
可能是个好主意,因为它定义了单个城市,而不是城市的集合。
当你写下这行代码时
List<Cities> cities = new List<Cities>();
您实例化一个对象作为“城市”列表。列表是一种“通用”类型。这意味着它能够处理任何类型并且行为相同。您可以有一个 List 或 List,您将操作不同的对象,但 List 的行为保持不变。您不是将 Cities“传递”给 List 构造函数,而是将 List 本身视为一种类型。 例如,这相当于声明一个城市数组。您的列表中还没有数据,但已准备好接收多个城市实例。
然后当你写的时候
cities.Add(New Cities{prop1=value,prop2=value...});
在运行时它会做类似的事情
var c = new Cities();
c.prop1=value;
c.prop2=value;
cities.Add(c);
这是一种快捷方式,也使代码更具可读性。