c# - 更改列表中的变量时如何修改原始变量?C#
问题描述
假设我有这段代码(这是一个例子):
int test = 5;
List<int> testlist = new List<int>();
testlist.Add(test);
test = 7;
Console.WriteLine(testlist[0]);
这给出了输出:5。我想要的是 7。
我怎样才能使列表中的元素与原始元素相同?换句话说,当我更改原始值时,我希望它也更改列表中的元素,反之亦然。在 C++ 中,我会创建一个指针向量。AFAIK C# 中没有指针类型,那么解决方法是什么?
解决方案
像这样使用,
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。
推荐阅读
- python - 与 django Rest 相关的多对多
- generics - Kotlin如何确保泛型参数是接收器类的超类
- sql - SQL Oracle IN 运算符行为
- php - 无法阻止 Laravel 限制 circleci 上的功能测试
- sql - SSIS 将指数转换为实数 (DT_R4)
- javascript - 在 ABAP 中加密字符串并在 JavaScript 中解密
- reactjs - react-redux 错误消息传递最佳实践
- xamarin.forms - 如何在不使用 Xamarin.forms 中的单例的情况下保留共享数据
- php - 表单应该在使用 PHPMailer 发送邮件之前进行验证
- prometheus - 设置 Netdata -> Consul -> Prometheus Stack