首页 > 解决方案 > 如何使用交换方法交换类列表中存在的长变量

问题描述

我有一个清单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 传递。

我可以使用局部变量并为其赋值并使用它,但我正在寻找一个全局解决方案。

标签: c#

解决方案


您可以做的是通过引用使属性返回:

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


推荐阅读