我想根据索引变量 (orderIndex) 访问类的三个成员 (_orderDay、_orderCustody、_orderBox),使用与以下方法不同的方法示例
public class COrdering
{
private int _orderDay;
private int _orderCustody;
private int _orderBox;
public COrdering() { _orderDay = _orderCustody = _orderBox = 0; }
public int IncOrder(int orderIndex)
{
int v = orderIndex == 0 ? _orderDay : (orderIndex == 1 ? _orderCustody : _orderBox);
v++;
if (orderIndex == 0) _orderDay = v
else if (orderIndex == 1) _orderCustody = v;
else _orderBox = v;
return v;
}
}
这个想法是使用比前一个示例更少的编码。当我在 C++ 中编写类似的代码时,我使用 std::bind 创建一个对所涉及的每个字段的引用的 const 数组,但我不知道如何在 C# 中制作类似的代码。谁能帮我解决这个问题吗?
编辑
我找到了一种优化 IncOrder
方法的方法:
//...
private int _incDay() { return ++_orderDay; }
private int _incCustody() { return ++_orderCustody; }
private int _incBox() { return ++_orderBox; }
private IReadOnlyList<Func<int>> _funcs = Array.AsReadOnly(new Func<int>[] {_incDay, _incCustody, incBox});
public int IncOrder(int orderIndex) { return _funcs[orderIndex](); }
可能还有另一种方法,例如创建对这些字段的引用数组,但我不知道这是否可行。
最佳答案
听起来像是索引运算符重载的工作:
public int this[int index] => IncOrder(index);
用法:
COrdering ordering = new COrdering();
int newValue = ordering[0];
更新 - 您可以在内部使用数组
public class COrdering
{
public enum OrderIndex { Day = 0, Custody = 1, Box = 2, NumElements };
private readonly int[] values = new int[(int)OrderIndex.NumElements];
public int IncOrder(OrderIndex orderIndex) => ++values[(int)orderIndex];
public int this[OrderIndex index] => IncOrder(index);
}
此外,您的构造函数可以被删除,在 C# 中,所有内容都会自动初始化为 0(或引用类型为 null)。
关于c# - 引用几位类(class)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65395916/