How to copy one element of a generic collection
I need to copy one element o开发者_JS百科f a generic collection and add it to the list. Something similar to this:
private List<CalculationResult> cantileverResults = new List<CalculationResult>();
cantileverResults.Add(cantileverResults[previousIndex]);
The problem with this solution is that when I modify the new element, the previousIndex element changes as well. I believe this is because they are reference-type, not value-type. How can I just copy (clone?) the information from one element to another without affecting each other any further?
You will need to create a new
object when adding it.
This can be done in several ways - a helper method that takes an object of your type (CalculationResult
) and returns a completely new one.
Perhaps have a constructor overload that does this.
There are many ways to achieve such a thing - implementing ICloneable
and having the Clone
method return a new object.
For example, if you were to create a constructor overload, this is how you could use it:
cantileverResults.Add(new CalculationResult(cantileverResults[previousIndex]));
精彩评论