namespace Modbus.Data
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
///
/// A 1 origin collection represetative of the Modbus Data Model.
///
public class ModbusDataCollection : Collection
{
private bool _allowZeroElement = true;
///
/// Initializes a new instance of the class.
///
public ModbusDataCollection()
{
AddDefault(this);
_allowZeroElement = false;
}
///
/// Initializes a new instance of the class.
///
/// The data.
public ModbusDataCollection(params TData[] data)
: this((IList)data)
{
}
///
/// Initializes a new instance of the class.
///
/// The data.
public ModbusDataCollection(IList data)
: base(AddDefault(data.IsReadOnly ? new List(data) : data))
{
_allowZeroElement = false;
}
internal ModbusDataType ModbusDataType { get; set; }
///
/// Inserts an element into the at the specified
/// index.
///
/// The zero-based index at which item should be inserted.
/// The object to insert. The value can be null for reference types.
///
/// index is less than zero.-or-index is greater than
/// .
///
protected override void InsertItem(int index, TData item)
{
if (!_allowZeroElement && index == 0)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"0 is not a valid address for a Modbus data collection.");
}
base.InsertItem(index, item);
}
///
/// Replaces the element at the specified index.
///
/// The zero-based index of the element to replace.
/// The new value for the element at the specified index. The value can be null for reference types.
///
/// index is less than zero.-or-index is greater than
/// .
///
protected override void SetItem(int index, TData item)
{
if (index == 0)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"0 is not a valid address for a Modbus data collection.");
}
base.SetItem(index, item);
}
///
/// Removes the element at the specified index of the .
///
/// The zero-based index of the element to remove.
///
/// index is less than zero.-or-index is equal to or greater than
/// .
///
protected override void RemoveItem(int index)
{
if (index == 0)
{
throw new ArgumentOutOfRangeException(
nameof(index),
"0 is not a valid address for a Modbus data collection.");
}
base.RemoveItem(index);
}
///
/// Removes all elements from the .
///
protected override void ClearItems()
{
_allowZeroElement = true;
base.ClearItems();
AddDefault(this);
_allowZeroElement = false;
}
///
/// Adds a default element to the collection.
///
/// The data.
private static IList AddDefault(IList data)
{
data.Insert(0, default(TData));
return data;
}
}
}