【问题标题】:Correct way to change value of an item in a list of class objects更改类对象列表中项目值的正确方法
【发布时间】:2013-07-05 19:55:49
【问题描述】:

给定这样的课程:

 public class Dinosaur
{
    public string Specie { get; set; }
    public int Age { get; set; }
    public int Weight { get; set; }
    public Point Location { get; set; }

    // Constructor
    public Dinosaur()
    {

    }

还有一个像这样的列表:

        public static List<Dinosaur> Dinosaurs = new List<Dinosaur>();

更改列表最后一项中的值的正确方法是什么? 这会引发错误(“'System.Collections.Generic.List.this[int]' 的最佳重载方法匹配有一些无效参数”):

Dinosaurs[Dinosaurs.Last()].Location.X = pixelMousePositionX;

一如既往,提前致谢! Stackoverflow 一直是这个项目的救星。

【问题讨论】:

  • 你必须通过它的索引来引用项目...也许试试Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;Dinosaurs.Last.Location.X = pixelMousePositionX;
  • 进行了更改,现在它抛出此错误:无法修改“DinosaurIsland.Dinosaur.Location”的返回值,因为它不是变量。

标签: c# list class


【解决方案1】:

Dinosaurs.Last() 已经返回最后一项,因此您根本不需要索引器。

Dinosaurs.Last().Location.X = pixelMousePositionX;

现在它抛出这个错误:无法修改返回值 'DinosaurIsland.Dinosaur.Location' 因为它不是变量

这是因为Point 是一个结构而不是一个引用类型。所以你必须创建一个新点。

Point oldLocation = Dinosaurs.Last().Location;
Dinosaurs.Last().Location = new Point { X = pixelMousePositionX, Y = oldLocation.Y };

【讨论】:

  • 感谢您的快速回答。现在它抛出这个错误:Cannot modify the return value of 'DinosaurIsland.Dinosaur.Location' because it is not a variable.
  • 没错,在 C# 中,结构是不可变的(创建后无法更改)。 DataTime 是另一个很好的例子。
【解决方案2】:

Dinosaurs.Last() 返回最后一项,而不是它的索引,所以这样:

Dinosaurs.Last().Location.X = pixelMousePositionX;

如果你想通过索引来做,那么这个:

Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;

【讨论】:

  • 感谢您的快速回复。知道为什么现在抛出此错误:无法修改“DinosaurIsland.Dinosaur.Location”的返回值,因为它不是变量。
【解决方案3】:

鉴于您的操作方式,您必须通过它的索引来引用该项目:

Dinosaurs[Dinosaurs.Count - 1].Location.X = pixelMousePositionX;

或者直接引用对象:

Dinosaurs.Last().Location.X = pixelMousePositionX;

【讨论】:

  • 知道为什么现在抛出此错误:无法修改“DinosaurIsland.Dinosaur.Location”的返回值,因为它不是变量。
猜你喜欢
  • 2019-04-12
  • 2020-11-05
  • 2017-07-25
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2016-08-06
  • 2020-08-22
  • 1970-01-01
相关资源
最近更新 更多