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

C#中Item对象属性未正确赋值,循环输出价格始终为0的解决方法

解决C#对象属性赋值后输出始终为0的问题

我编写的C#代码如下,当遍历列表时,控制台始终输出0,而非我为first和second对象设置的实际价格。请问该如何正确设置对象的属性值?

public static List<Item> itemList = new List<Item>();
public class Item
{
    public int id;
    public int price, stock;
    public Item(int id, int price, int stock)
    {
        id = this.id;
        price = this.price;
        stock = this.stock;
    }
}
static void Main(string[] args)
{
    Item first = new Item(1, 23, 2);
    Item second = new Item(2, 345, 5);
    itemList.Add(first);
    itemList.Add(second);
    foreach(var item in itemList)
    {
        Console.WriteLine(item.price);
    }
}

问题根源

你在Item类的构造函数里赋值顺序完全搞反了!

目前你写的代码是把类的成员变量(默认初始值为0)赋值给了构造函数的参数,而不是把传入的参数值赋值给类的成员变量。相当于你根本没给id、price、stock这些属性设置你传入的数值,所以它们一直保持默认的0值。

修正后的代码

只需要把构造函数里的赋值顺序反过来,用this关键字明确指定类的成员变量,接收参数的值:

public static List<Item> itemList = new List<Item>();
public class Item
{
    public int id;
    public int price, stock;
    public Item(int id, int price, int stock)
    {
        // 修正:把参数值赋给类的成员变量
        this.id = id;
        this.price = price;
        this.stock = stock;
    }
}
static void Main(string[] args)
{
    Item first = new Item(1, 23, 2);
    Item second = new Item(2, 345, 5);
    itemList.Add(first);
    itemList.Add(second);
    foreach(var item in itemList)
    {
        Console.WriteLine(item.price); // 现在会输出23和345
    }
}

额外优化建议

为了避免以后再犯类似的混淆错误,你可以试试这些写法:

  • 给成员变量加前缀:比如把类的成员变量命名为_id、_price,这样构造函数里写_id = id;就不会搞混了
  • 使用自动属性:C#推荐用属性而非公共字段,写法更简洁也更符合规范:
    public class Item
    {
        public int Id { get; set; }
        public int Price { get; set; }
        public int Stock { get; set; }
    
        public Item(int id, int price, int stock)
        {
            Id = id;
            Price = price;
            Stock = stock;
        }
    }
    
  • C# 6+的简化构造函数:可以用元组赋值的方式进一步简化:
    public Item(int id, int price, int stock) => (Id, Price, Stock) = (id, price, stock);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:18:10