【问题标题】:How do I store the values of an object type in an array and call them (C#)?如何将对象类型的值存储在数组中并调用它们(C#)?
【发布时间】:2020-08-24 06:30:15
【问题描述】:

我有以下课程:

public class Object
    {
        public string Name { get; set; }
        public int Price { get; set; }
    }

我创建了一个新的对象数组: Object[] Object= new Object[1];

我给它赋值,Object[0] = new Object() { Name = "T", Price = 32};

但是,当我尝试打印值时,像这样使用 foreach:

foreach(var a in Object) 
Console.WriteLine(a);

我得到了 Namespace.Object;

如何解决此问题并获取每行名称和价格的实际值并存储多个值?

【问题讨论】:

  • 首先我建议找一个比Object 更好的名字。但基本上你需要重写ToString 方法。

标签: c# arrays loops sorting for-loop


【解决方案1】:

Console.WriteLine() 将尝试将a 转换为字符串,进而调用a.ToString()

如果需要,您可以override the ToString() method

public class Object
{
    public string Name { get; set; }
    public int Price { get; set; }

    public override string ToString()
    {
        return $"[Name: {Name}, Price: {Price}]";
    }
}

【讨论】:

    【解决方案2】:

    Object 类中的override .ToString() 方法不是打印实例,而是在打印时将您的对象转换为string

    //First of all, give meaningful name
    public class Product
    {
       public string Name { get; set; }
       public int Price { get; set; }
    
        public override string ToString()
        {
            return $"Price of product {this.Name} is {this.Price}";
        }
    }
    

    现在只需迭代每个产品。 Console.WriteLine() 将在内部调用您在 Product 类中覆盖的 ToString()

     //Here Products is array of Product object
     foreach(var product in Products) 
        Console.WriteLine(product);
    

    【讨论】:

    • Console.WriteLine 将在内部调用ToString,因此您不必显式调用它。
    • 哦,我不知道。谢谢@juharr 每天都是上学日;)
    猜你喜欢
    • 2019-09-05
    • 2021-12-21
    • 2013-10-06
    • 2016-11-27
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多