更改一个变量也会更改另一个变量。防止变量具有相同的引用

发布于 2024-11-08 23:02:24 字数 567 浏览 3 评论 0原文

我有一个类,构造函数需要一个类和其他类似的东西:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝颜夕 2024-11-15 23:02:24

您可以创建 listParam 的副本,而不仅仅是分配其引用:

tempList = listParam.ToList();

请注意,这不会创建列表中每个对象的副本,而只是创建对这些对象的引用。

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.

高冷爸爸 2024-11-15 23:02:24

接受 IEnumerable,而不是接受 List。如果您想要一个具体的列表,请对其调用 .ToList()

原始来源不受影响,并且您有一个副本。您还可以享受任何支持该接口的好处。

编辑:我读错了问题中的代码,你的副本属于同一类。嗯,它在两个地方,类调用者。我坚持我的建议,但是,是的,您需要两次调用 .ToList(),每个副本调用一次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文