[英]C# instantiating class object & adding to List
如何創建Country的新實例,該實例使用3個變量firstParam,secondParam,thirdParam作為其構造函數,並添加到List countryList中?
正在從.txt中讀取這3個變量,並分別在阿富汗,喀布爾,30419928阿爾巴尼亞,地拉那,2821977中拆分
我的3個拆分變量firstParam,secondParam,thirdParam包含正確的信息。 我認為我在添加到countryList時犯了語法錯誤,因為調試模式逐步遍歷變量會加載正確的信息,但是當我在countryList上嘗試foreach時,會得到輸出“ countries.country”。
List<Country> countryList = new List<Country>();
foreach (string line in lines)
{
string[] criteria = line.Split(',');
string firstParam = "";
string secondParam = "";
int thirdParam = 1;
firstParam = criteria[0];
secondParam = criteria[1];
thirdParam = Convert.ToInt32(criteria[2]);
countryList.Add(new Country(firstParam, secondParam, thirdParam));
}
我沒有想法,也不確定要嘗試什么,我想進一步了解構圖,但希望有人可以推動我前進。 謝謝。
如果要選擇調試值,則應使用“ Override ToString()”或“ DebuggerDisplayAttribute”方法。
//DebuggerDisplayAttribute
[DebuggerDisplay("Value = {Display}")]
public class Country
{
public string Name { get; set; }
public string City { get; set; }
public string Display
{
get => $"{Name}, {City}";
}
//Override ToString()
public override string ToString()
{
return $"{Name}, {City}";
}
}
嘗試執行此操作以驗證您的代碼是否按照您希望的方式工作:
List<Country> countryList = new List<Country>();
foreach (string line in lines)
{
string[] criteria = line.Split(',');
countryList.Add(new Country(criteria[0],
criteria[1],
Convert.ToInt32(criteria[2]))
}
Console.WriteLine($"Countries in countryList: {countryList.Count}.");
foreach ( Country country in countryList)
{
Console.WriteLine($"Name: {country.Name}, Capital: {country.Capital}, Population: {country.Population}.");
}
您可能需要為Country類的字段插入自己的名稱,而不是Name,Capital和Population。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.