You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何在每次创建对象时添加到List<>,通过IComparable按价格排序后打印

C# 实现方案

1. 定义Customer类(实现IComparable接口+自动存入列表逻辑)

using System;
using System.Collections.Generic;

public class Customer : IComparable<Customer>
{
    // 实例属性
    public string Name { get; set; }
    public decimal Price { get; set; }

    // 静态公共列表,存储所有创建的Customer实例
    public static List<Customer> AllInstances { get; private set; } = new List<Customer>();

    // 构造函数:创建对象时自动把当前实例加入静态列表
    public Customer(string name, decimal price)
    {
        Name = name;
        Price = price;
        AllInstances.Add(this);
    }

    // 实现IComparable接口的比较逻辑,按Price字段升序排序
    public int CompareTo(Customer other)
    {
        if (other == null) return 1;
        return this.Price.CompareTo(other.Price);
    }

    // 重写ToString方法,方便直接打印对象内容
    public override string ToString()
    {
        return $"姓名:{Name},价格:{Price}";
    }
}

2. 调用测试代码

// 创建对象,会自动存入Customer.AllInstances列表,注意同作用域不要使用重复变量名
Customer obj1 = new Customer(name:"abc", price:23);
Customer obj2 = new Customer(name:"efg", price:45);

// 按Price排序:因为已经实现了IComparable接口,直接调用Sort方法即可
Customer.AllInstances.Sort();

// 遍历打印整个列表
foreach (var item in Customer.AllInstances)
{
    Console.WriteLine(item);
}

补充说明

  • 如果需要按Price降序排序,只需要把CompareTo方法的返回值改成other.Price.CompareTo(this.Price)即可
  • 静态列表AllInstances全局共享,程序运行过程中所有创建的Customer对象都会自动存入,不需要手动调用Add方法
  • 如果不需要自动存入逻辑,也可以手动声明一个本地List<Customer>,每次创建对象后手动调用Add方法添加

内容的提问来源于stack exchange,提问作者Saloni Parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:48:01