开发者

How do I create a copy of an object?

I have a object named post and I declare a ne开发者_运维百科w variable named newPost as type post object and then

var newPost = post

but when I Modify any properties of post object, that Modified Influences properties of newPost object.

How do I solve this problem?


What you need to do is one of a number of possible things. Here are a couple for consideration.

  1. Implement IClonable and do var newPost = post.Clone();
  2. Have a constructor on the class that has another instance as a paramenter, then copy the properties from the instance passed in to the new instance. i.e. var newPost = new Post(post);

One gotcha to look out for, you probably will want to do what's known as a deep clone or deep copy of the object, so that if your class has any object properties the two instances aren't pointing to the same reference for their properties.


You need to provide some way to clone the object. As other commenter said, you are just referencing the same object. See this StackOverflow Question (first answer) for details Deep cloning objects


This is an extremely basic question, and I can't write a book on it...

But that's exactly how it is supposed to work. You are setting 'reference' variables; newPost and post both refer to the exact same object which is a class and therefore a Reference type, so you should expect that all changes to one also affect the other.

It sounds like you need to pick up a good basic .NET programming book, and pay particular attention to the differences between Value and Reference types.

The 'solution' is to create a new object and set/copy the individual members of the old object to the new one, but I fear that solution will not serve you too long before you dig some more into things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜