c# - 如何使用交换方法交换类列表中存在的长变量
问题描述
我有一个清单public List<ArticleWarehouseLocations> ArticleWarehouseLocationsList
。在此列表中,我有一个名为Position
.
`Swap<long>(ref ArticleWarehouseLocationsList[currentIndex].Position, ref ArticleWarehouseLocationsList[currentIndex - 1].Position);`
public void Swap<T>(ref T lhs, ref T rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
我正在尝试做这样的事情。它给了我一个错误属性或索引可能不会作为 ref 或 out 传递。
我可以使用局部变量并为其赋值并使用它,但我正在寻找一个全局解决方案。
解决方案
您可以做的是通过引用使属性返回:
class Obj {
private long pos;
public ref long Position { get { return ref pos; } }
}
static void Main(string[] args)
{
Obj[] arr = new Obj[2] { new Obj(), new Obj() };
arr[0].Position = 10;
arr[1].Position = 20;
int index = 0;
WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
Swap<long>(ref arr[index].Position, ref arr[index+1].Position);
WriteLine($"{arr[index].Position}, {arr[index+1].Position}");
}
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns
推荐阅读
- python - 尝试从数据集中提取 y_val 会抛出“所有输入数组必须具有相同的维数”
- xcode - Xcode 12“显示库”命令不再显示可能要添加的视图
- c# - StackExchange.Redis 哨兵操作
- css - 从图像混合 sass 自动生成渐变颜色
- reactjs - 强制选择行
- fortran - 尝试使用 f2py 围绕两个 C 对象编写 Fortran 包装器时出现分段错误
- reactjs - 添加更多数据后,带有 reduxjs Web 应用程序的 ReactJs 变慢
- javascript - 拆分日期的 Javascript 字符串并按年份分组
- javascript - 在 D3.js 中重新定位地图后重置拖动位置
- python - Python - 从字符串执行 getter 链