首页 > 解决方案 > 更改列表中的变量时如何修改原始变量?C#

问题描述

假设我有这段代码(这是一个例子):

int test = 5;
List<int> testlist = new List<int>();
testlist.Add(test);
test = 7;
Console.WriteLine(testlist[0]);

这给出了输出:5。我想要的是 7。

我怎样才能使列表中的元素与原始元素相同?换句话说,当我更改原始值时,我希望它也更改列表中的元素,反之亦然。在 C++ 中,我会创建一个指针向量。AFAIK C# 中没有指针类型,那么解决方法是什么?

标签: c#listpointersvariables

解决方案


像这样使用,

        int test = 5;
        List<int> testlist = new List<int>();
        test = 7; // this line need to come up
        testlist.Add(test); // This line comes after test = 7;
        Console.WriteLine(testlist[0]);

现在你可以得到输出 7。


推荐阅读