C# 确定使用c设置数组属性的哪个索引#

C# 确定使用c设置数组属性的哪个索引#,c#,arrays,properties,indexing,C#,Arrays,Properties,Indexing,我正在创建一个OPC客户端,通过它可以读取电气设备的标签。这是通过在OPC组中设置项目来完成的。我想要一个属性,它是bool[]的数组,用于将项目设置为活动或非活动。我需要知道此属性bool[]的哪个索引用于设置该属性,以便我可以使用它来激活该项。我可以只使用一个方法,但更喜欢一个属性_组是保存项目的OPC组 private bool[] _ItemActive; public bool[] itemActive { get { return _ItemActive; }

我正在创建一个OPC客户端,通过它可以读取电气设备的标签。这是通过在OPC组中设置项目来完成的。我想要一个属性,它是bool[]的数组,用于将项目设置为活动或非活动。我需要知道此属性bool[]的哪个索引用于设置该属性,以便我可以使用它来激活该项。我可以只使用一个方法,但更喜欢一个属性_组是保存项目的OPC组

private bool[] _ItemActive;    
public bool[] itemActive {
    get { return _ItemActive; }
    set {
        if (_theGroup != null) {
            int itemIndex = ?? // I don't know how to find property index access by user
            int itemHandle = itemHandles[itemIndex]; //uses index to discover handle
            _theGroup.SetActiveState(itemHandle, value, out err); // use handle to set item active
        }
        _ItemActive = value;
    }
}
用户会这样做

opcClient.itemActive[3] = false;

我需要能够发现3并将其插入上面所示的bool[]数组的setter中的itemIndex中。

您可以使用重写索引器操作符创建自定义集合,在其中执行自定义逻辑。但是创建setter方法
SetItemActivation(int,bool)
似乎是一个更干净的解决方案。

我找到了一个解决方案:创建一个新类,其实例跟踪其条目的更改;每当一个索引值被更改时,就会触发一个事件,告知哪个条目被更改以及更改为什么值。下面是这样一个类(当然,下面的代码可以使用泛型来代替bools,使其更加通用):

接下来实现OPC类:

class OPC_client{
  // Tracked bool array
  public BoolArray_Tracked ItemActive{get; set;}

  // Constructor
  public OPC_client(bool[] boolItemActive){
    ItemActive = new BoolArray_Tracked(boolItemActive);
    ItemActive.RaiseIndexEvent += Handle_ItemActive_IndexChange;
  }

  // State what should happen when an item changes
  private void Handle_ItemActive_IndexChange(object sender, IndexEventArgs e){
    //if (_theGroup != null) {//Your code in the question
      int itemIndex = e.Index; 
      //int itemHandle = itemHandles[itemIndex]; //Your code
      //_theGroup.SetActiveState(itemHandle, value, out err); // Yours
    //} //Your code

    Console.WriteLine("The array `ItemActive' was changed"
      + " at entry " + itemIndex.ToString() 
      + " to value " + e.Value.ToString());
  }
}
最后实现一个简单的程序来测试这一点

static void Main(string[] args){
  OPC_client opcTest = new OPC_client(new bool[]{true, false});
  Console.WriteLine("Testing if message appears if value stays the same");
  opcTest.ItemActive[0] = true;

  Console.WriteLine();
  Console.WriteLine("Testing if message appears if value changes");
  opcTest.ItemActive[0] = false;
  Console.ReadLine();
}

我需要能够在类实例化之前和之后设置活动状态。第一个组将为null,因此它将只设置属性。然后,当组启动时,它会使用此属性来确定它们是否应该启动为活动状态。然后,在组运行且不为null之后,我必须使用组的SetActiveState方法激活它。所以我试着让一个地产同时做这两件事。但我同意setter方法会更干净。。。
static void Main(string[] args){
  OPC_client opcTest = new OPC_client(new bool[]{true, false});
  Console.WriteLine("Testing if message appears if value stays the same");
  opcTest.ItemActive[0] = true;

  Console.WriteLine();
  Console.WriteLine("Testing if message appears if value changes");
  opcTest.ItemActive[0] = false;
  Console.ReadLine();
}