如何用交换方法交换类列表中的长变量

  • 本文关键字:交换 变量 何用 方法 列表 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或退出。

我可以使用本地变量并分配值并使用它,但我正在寻找一个全局解决方案。

您可以做的是通过参考返回属性:

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://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-ships-and-scrupts/ref-returns

我相信,在评论中提出的元组交换(x, y) = (y, x)是必须的,但想与Linq Expressions分享另一个apreach(有点太长以发表评论,因此将其作为答案发布为答案(

public static void SwapProperties<T>(T lhs, T rhs, Expression<Func<T, object>> propExpression)
{
    var prop = GetPropertyInfo(propExpression);
    var lhsValue = prop.GetValue(lhs);
    var rhsValue = prop.GetValue(rhs);
    prop.SetValue(lhs, rhsValue);
    prop.SetValue(rhs, lhsValue);
}
private static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> propExpression)
{
    PropertyInfo prop;
    if (propExpression.Body is MemberExpression memberExpression)
    {
        prop = (PropertyInfo) memberExpression.Member;
    }
    else
    {
        var op = ((UnaryExpression) propExpression.Body).Operand;
        prop = (PropertyInfo) ((MemberExpression) op).Member;
    }
    return prop;
}
class Obj
{
    public long Position { get; set; }
    public string Name { get; set; }
}
public static void Main(string[] args)
{
    var a1 = new Obj()
    {
        Position = 10,
        Name = "a1"
    };
    var a2 = new Obj()
    {
        Position = 20,
        Name = "a2"
    };
    SwapProperties(a1, a2, obj => obj.Position);
    SwapProperties(a1, a2, obj => obj.Name);
    Console.WriteLine(a1.Position);
    Console.WriteLine(a2.Position);
    Console.WriteLine(a1.Name);
    Console.WriteLine(a2.Name);
}

最新更新