简体   繁体   English

C#类对象列表更改为匹配最后一个对象?

[英]C# list of class objects changing to match last object?

I am trying to make an 'archive' of all past versions of a class (or struct, for that matter). 我试图为一个类的所有过去版本(或结构)做一个“档案”。 But as a class is created to be added to the list, it seems the sum total of listed classes alter themselves to match. 但是,当创建一个要添加到列表中的类时,似乎列出的类的总和会自行更改以匹配。

My code goes along something like this: 我的代码是这样的:

public class State
{
  public int i;

  public State(int newI)
  {
    i = newI;
  }
}

List<State> list = new List<State>;

public void NewEntry(int x)
{
  State state = new State(x); //this is the line in question
  list.Add(state)
}

By the time the State constructor has executed, all states in list have been changed to match their i to the fresh value of x. 到State构造函数执行时,列表中的所有状态均已更改,以使其i与x的新值匹配。

What am I missing, besides basic knowledge and understanding? 除了基本知识和理解之外,我还缺少什么? :P :P

Uhm... Is not very clear from your example, but let me guess what the problem is. 嗯...从您的例子中还不是很清楚,但是让我猜出问题出在哪里。

When you add the class to the list, you may be adding a reference. 当您将类添加到列表时,您可能正在添加引用。

When you use: 使用时:

State x = new State();
State b = x;

box "x" and "b" points to same object, xi and bi are the same memory. 框“ x”和“ b”指向相同的对象,xi和bi是相同的存储器。

IF and if State is a struct, then it's different IF如果国家是一个结构,那么它的不同

public **struct** State
{
  public int i;

  public State(int newI)
  {
    i = newI;
  }
}

Then 然后

State x = new State();
State b = x;

will make a copy of every value field (like ints and doubles) and xi will be in a different memory location than bi 将复制每个值字段(如ints和doubles),并且xi将位于与bi不同的内存位置

Is this related to your issue? 这与您的问题有关吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM