我是編程新手,每次在 list<> 中創建物件時都嘗試添加物件。
Customer obj = new Customer(name="abc",price=23);
Customer obj = new Customer(name="efg",price=45);
我希望將價格和名稱添加到串列中,并希望使用 Icomparable 介面對價格進行排序。誰能解釋一下,謝謝
uj5u.com熱心網友回復:
根據我從您的問題中了解到的,您可以將靜態串列添加到您的 Customer 類中,并將價格添加到建構式內的串列中。因此,每次您創建該類的物件時,價格都會添加到您的串列中。
客戶類別 -
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);
}
uj5u.com熱心網友回復:
順便說一句,您知道如何使用 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);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323420.html
