首页 > 解决方案 > 引用几个类成员

问题描述

我想根据和索引变量(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](); }

可能还有另一种方法,例如创建对这些字段的引用数组,但我不知道这是否可能。

标签: c#

解决方案


听起来像是索引运算符重载的工作:

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)。


推荐阅读