更改列表中元素的属性不会更改它

时间:2015-01-19 09:52:23

标签: c#

我对未存储的值感到困惑。这是一个类的实例,其成员定义如下。

public class MyHolder
{
    public List<MyPart> Parts { get; set; }
}

public class MyPart
{ 
    public bool Taken { get; set; }
    public int Id { get; set; }
}

我尝试探测该类以获取已接受元素的ID,但它并不起作用,因为我所做的更新似乎无法通过。所以我创造了以下非常简单的探测器。

List<int> before = myHolder.Where(e => e.Taken).Select(f => f.Id).ToList();
myHolder.First(p => p.Id == 7).Taken = false;
List<int> before = myHolder.Where(e => e.Taken).Select(f => f.Id).ToList();

令我惊讶的是,beforeafter的数量保持不变!我已经验证了所有 ID,我已确认例如7从一开始就是true。我甚至尝试使用false启动它,然后将其设置为true。到目前为止,我看不到其他任何逻辑。我肯定知道它是做错了什么,但我不确定它是什么。并且很难搜索它,因为这种奇怪的行为非常通用。

它不像我们创建myHolder的副本并将更新后的值放入其中。如果是这样,我怎样才能获得并写入真实的东西

我希望有人看到明显的东西。或者至少指出一个很好的方向来搜索更多。

2 个答案:

答案 0 :(得分:0)

你的意思是这样的:

public class MyHolder
{
    public List<MyPart> Parts { get; set; }
}

public class MyPart
{
    public int Id { get; set; }
    public bool Taken { get; set; }
    public string Name { get; set; }
}   

此代码更新按预期工作

var myHolder = new MyHolder {
    Parts = new List<MyPart> {
        new MyPart { Id = 7, Taken = true, Name = "Test" },
        new MyPart { Id = 8, Taken = false, Name = "Test 1" }
    }
};

var before = myHolder.Parts.Where(e => e.Taken).Select(f => f.Id).ToList();
Console.WriteLine(before.Count());

myHolder.Parts.First(p => p.Id == 7).Taken = false;

var after = myHolder.Parts.Where(e => e.Taken).Select(f => f.Id).ToList();
Console.WriteLine(after.Count());

见工作fiddle

答案 1 :(得分:0)

这对我有用 -

public class MyHolder
{
    public List<MyPart> Parts { get; set; }
}

public class MyPart
{
    public int Id { get; set; }
    public bool Taken { get; set; }
    public string Name { get; set; }
}



var holder = new MyHolder() { Parts = new List<MyPart>() { new MyPart() { Id = 7, Name = "R", Taken = true }, new MyPart() { Id = 8, Name = "S", Taken = true }, new MyPart() { Id = 9, Name = "T", Taken = true } } };

List<int> before = holder.Parts.Where(m => m.Taken).Select(f => f.Id).ToList();
holder.Parts.First(p => p.Id == 7).Taken = false;
List<int> after = holder.Parts.Where(m => m.Taken).Select(f => f.Id).ToList();