c# - 将布尔数组转换为计数器
问题描述
我有一个大小为 12 的布尔数组。在任何时候,只有一个索引为真。数组连接到旋钮上的 12 位置,从 0 到 11。如果我们将旋钮从位置 5 顺时针移动到 6,数组中的索引 5 将变为 false,索引 6 将为 True。11 位后旋钮将移回 0。
我想创建一个随着旋钮顺时针或逆时针移动而增加或减少的计数器。如果位置从 11 变为 0,计数器也将继续增加。类似地,从 0 移动到 12 时,计数器将减小。
以非常简单的方式,我希望布尔数组表现得像一个旋转编码器。
解决方案
I wouldn't do it with an array. Create an object that has this specific functionality
public class RotaryEncoder {
private int totalPositions:
public int ActiveIndex = { get; private set; }
public RotaryEncoder(int totalPositions) {
this.totalPositions = totalPositions;
this.ActiveIndex = 0;
}
public void IncreasePosition() {
ActiveIndex = ActiveIndex + 1 == totalPositions ? 0 : ActiveIndex + 1;
}
}
You get the idea on how to decrease position. The boolean array itself has no extra properties as active index.
A different approach, would have you create a collection of new objects that held both a boolean and an index and change both the active and new active item at once. (Surely less efficient).
If course, you would again have to encapsulate then into a class, as you don't want implementation details to leak out and let consumers handle your data structure as they please.
推荐阅读
- codeigniter-3 - 需要在 CodeIgniter 中添加字体系列
- c++ - 为什么存储对成员函数的调用的 std::function 可以有两种不同的可调用类型
- android - Android中的对象空
- java - 如何使用 Apache HTTPClient 将附件正确上传到 RTC (IBM Jazz)?
- powerbi - 当我已经连接到 Analysis Services 时,如何在 power bi 中添加其他数据?
- python - PySpark:为数据帧操作转换配置字符串项
- google-analytics-4 - 自定义 GA4 事件中的通过日期
- cookies - 无法在新打开的选项卡中设置 cookie (Safari 14)
- jquery - formData在文件上传ajax laravel上返回空对象
- php - 标识符值或配置无效