【问题标题】:Value is never set on Object C# [duplicate]永远不会在对象 C# 上设置值 [重复]
【发布时间】:2021-01-30 11:29:56
【问题描述】:
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);
  }
}

当我遍历列表时,它总是打印出 0,而不是我的第一件和第二件物品的实际价格。如何正确设置值?

【问题讨论】:

  • 你应该把它移到左边,像this.id = id, and alle others
  • price = this.price; 在此行之前,检查price 参数的值。在此行之后,检查price 参数的值。你注意到了什么?

标签: c# list object


【解决方案1】:

构造函数中对成员变量赋值的语句应该是

this.id = id

其中this 用于限定类成员字段/属性。

您可以在here 阅读有关this 用法的信息

public Item(int id, int price, int stock) 
{
    this.id = id;
    this.price = price;
    this.stock = stock;
}

【讨论】:

    【解决方案2】:

    因为在你的Item class 和构造函数中你写了相反的 你必须写这个构造函数:

     public Item(int id, int price, int stock)
      {
        this.id = id;
        this.price = price;
        this.stock = stock;
      }
    

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 2011-07-23
      • 2015-02-02
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多