繁体   English   中英

C#实例化类对象并添加到列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM