我有一个列表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传递。
我可以使用局部变量并为其分配值并使用它,但是我正在寻找全局解决方案。
答案 0 :(得分:2)
您可以做的是使属性通过引用返回:
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
答案 1 :(得分:1)
我相信注释中提出的元组交换(x, y) = (y, x)
是可行的方法,但是我想与LINQ Expressions分享另一个方法(注释太长了,所以可以发表答案)
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);
}