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](); }
可能还有另一种方法,例如创建对这些字段的引用数组,但我不知道这是否可能。
解决方案
听起来像是索引运算符重载的工作:
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)。
推荐阅读
- postgresql - Postgres:在一行中创建角色
- html - AngularJS中的Ajax调用没有从JSON文件中获取数据
- xml - 如何将 xml 字符串从 REST Web 服务发送到 JSP
- ionic3 - 离子 osmtogeojson 模块
- r - 了解 dnorm 和 geom_density
- arduino - 如何使用 Arduino Mega 2560 中内置的 MAX3421E USB 主机模块读取闪存驱动器?
- java - 为什么我的程序不能识别文本文件中的所有名称?
- linux - SED 删除带扩展名的单词
- python - 从字典中的所有值中减去 1
- verilog - Verilog 峰值检测