引用几个班级成员

时间:2020-12-21 15:57:01

标签: c#

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

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

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

为什么不使用 Dictionary<int, int>

public class COrdering
{
     Dictionary<int, int> map = new Dictionary<int, int>();
     public COrdering() { map[0] = 0; map[1] = 0; map[2] = 0; }

     public int IncOrder(int orderIndex)
     {
         return ++map[orderIndex];
     }
}

事实上,您甚至可以使用 int[]List<int>

答案 2 :(得分:-1)

我知道您想简化代码,因此在这种情况下,从保存数据的变量开始,如果您通过索引访问它们,则声明数组并使用枚举会更有意义,如下所示:

public class COrdering
{
    enum OrderType
    {
        Day = 0,
        Custody = 1,
        Box = 2,
        Count = 3
    };

    private int[] _order = new int[(int)OrderType.Count];

    public int IncOrder(OrderType orderIndex)
    {
        // Increment corresponding order type and return its value
        return ++_order[(int)orderIndex];
    }
}

您可以看到仅用一行代码就实现了 IncOrder。 ++ 必须在变量名之前,以便您得到正确的答案。我要么使用一个中间变量作为增量,要么在一个好的注释之前使用一个 ++,这样下一个程序员就会看到它。
[] 重载的另一种解决方案对于下一个调试您的代码的人来说是出乎意料和令人惊讶的 :-) 所以我想你猜我会选择哪个。