I have a class that the constructor requires a class and other things like:
public class SomeClass<T>
{
//global private variables for class
List<T> originalList = new List<T>;
List<T> tempList = new List<T>;
public SomClass(List<T> listParam, string name, ..etc)
{
originalList = listParam;
tempList = listParam;
originalList.removeAt(0); // this also removes an item from tempList.
}
}
I know this is because originalList and tempList have the same reference. How could I make them have diferent refer开发者_如何转开发ences. I use the tempList to filter results and whenever I want to refresh I use the originalList
You could make a copy of listParam
, rather than just assigning its reference:
tempList = listParam.ToList();
Note that this does not create a copy of each object in the list, but just a copy of the references to those objects.
Instead of accepting a List<T>
, accept an IEnumerable<T>
. If you then want a concrete list, call .ToList()
on it.
The original source is unaffected, and you have a copy. You also have the benefit of being able to take anything that supports the interface.
Edit: I misread the code in the question, your copy is in the same class. Well, it's in two places, the class and the caller. I stand by my suggestion, but yes, you'd need two invocations of .ToList()
, one for each copy.
精彩评论