【问题标题】:How to add a object value to list<> in c# every time object created and print the list at the end每次创建对象时如何在c#中将对象值添加到列表<>并在最后打印列表
【发布时间】:2021-10-16 05:14:03
【问题描述】:

我是编程新手,每次在列表中创建对象时都尝试添加对象。

Customer obj = new Customer(name="abc",price=23);
Customer obj = new Customer(name="efg",price=45);

我想将价格和名称添加到列表中,并想使用 Icomparable 接口对价格进行排序。 谁能解释一下,谢谢

【问题讨论】:

  • 请用正确的句子重新表述问题。完全不清楚您要达到的目标。

标签: c# .net list object icomparable


【解决方案1】:

根据我从您的问题中了解到的,您可以将静态列表添加到您的客户类中,并将价格添加到构造函数中的列表中。所以每次你创建一个类的对象时,价格都会被添加到你的列表中。

客户类 -

public class Customer
{
    public string name { get; set; }
    public int price { get; set; }

    public static List<int> prices = new();
    
    public Customer(string name, int price)
    {
        this.name = name;
        this.price = price;
        prices.Add(price);
    }
}

当您尝试打印时 -

Customer obj = new Customer(name: "abc", price: 23);
Customer obj1 = new Customer(name: "efg", price: 45);
foreach (var price in Customer.prices)
{
    Console.WriteLine(price);
}

【讨论】:

  • 顺便说一句,您知道如何使用 Icomparable 接口比较对象吗?我收到错误,因为 other.object 即将为空。
  • 请提供一些代码sn-p和问题细节(可能在另一个线程中)。我会尽力提供帮助。
【解决方案2】:

顺便说一句,您知道如何使用 IComparable 接口比较对象吗?一世 由于 other.object 即将为空,因此出现错误。

我猜你想比较我猜的价格?如果是,那么 id 建议您做一个通用列表,foreach 循环将字符串数组中的每个项目添加到列表中,构造函数正在通过该行。 我稍微“改造”了你的构造函数。为了比较,您可以使用接口 IComparable(也可以与 IEnumerable 一起使用),这也更容易为您将来维护

using System; using System.Collections.Generic; using System.IO;

namespace ConsoleApp25
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = {"abc;23","efg;45" };
            Customer[] customers = ReadFromStrArr(lines);
            Console.WriteLine(customers[0].price.CompareTo(customers[1].price));
        }

        static Customer[] ReadFromStrArr(string[] lines)
        {
            if (lines == null)
                throw new ArgumentNullException(nameof(lines));

            var result = new List<Customer>();

            foreach (var line in lines)
            {
                result.Add(new Customer(line));
            }

            return result.ToArray();
            
        }
    }
    public class Customer : IComparable<int>
    {
        public string name { get; set; }
        public int price { get; set; }

        

        public Customer(string line)
        {

            string[] data = line.Split(";");

            name = data[0];
            price = Convert.ToInt32(data[1]);

            // prices.Add(price); // ??
        }

        public int CompareTo(int other)
        {
            return price.CompareTo(other);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2017-06-16
    相关资源
    最近更新 更多