更改一个变量也会更改另一个变量。防止变量具有相同的引用
我有一个类,构造函数需要一个类和其他类似的东西:
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.
}
}
我知道这是因为originalList 和tempList 具有相同的引用。我怎样才能让他们有不同的参考文献。我使用 tempList 来过滤结果,每当我想刷新时,我都会使用 OriginalList
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 references. I use the tempList to filter results and whenever I want to refresh I use the originalList
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建
listParam
的副本,而不仅仅是分配其引用:请注意,这不会创建列表中每个对象的副本,而只是创建对这些对象的引用。
You could make a copy of
listParam
, rather than just assigning its reference:Note that this does not create a copy of each object in the list, but just a copy of the references to those objects.
接受
IEnumerable
,而不是接受List
。如果您想要一个具体的列表,请对其调用.ToList()
。原始来源不受影响,并且您有一个副本。您还可以享受任何支持该接口的好处。
编辑:我读错了问题中的代码,你的副本属于同一类。嗯,它在两个地方,类和调用者。我坚持我的建议,但是,是的,您需要两次调用
.ToList()
,每个副本调用一次。Instead of accepting a
List<T>
, accept anIEnumerable<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.