It is not related to GUI. I have a class with:
- Private
List
, which is edited inside the class. - Open
IReadOnlyCollection
property for access to privateList
- Public
event
for notification onList
changing
A list stores objects with properties. The class can changed an item's properties and notify about it. The user can only read an item's properties. I only picked this option.
class MortarInfo
{
public double Angle { get; private set; }
public bool State { get; private set; }
public MortarInfo(double angle, bool state)
{
Angle = angle;
State = state;
}
}
class Mortars
{
private List<MortarInfo> _mortarsInfo;
private ReadOnlyCollection<MortarInfo> _readOnlyMortarsInfo;
public Mortars()
{
_mortarsInfo = new List<MortarInfo>();
_readOnlyMortarsInfo = _mortarsInfo.AsReadOnly();
}
public ReadOnlyCollection<MortarInfo> MortarsInfo
{
get { return _readOnlyMortarsInfo; }
}
public event ListChangedEventHandler MortarsInfoChanged;
public void UpdateAngle(int index, double newAngle)
{
if (_mortarsInfo[index].Angle != newAngle)
{
_mortarsInfo[index] = new MortarInfo(newAngle, _mortarsInfo[index].State);
if (MortarsInfoChanged != null)
{
var arg = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
MortarsInfoChanged(this, arg);
}
}
}
}
1 Answer 1
It seems good but I have some comments on this,
Why do you create a new ListItem in every property change and not just replace to old property with the new one?
_list[index].Property1 = property1;
You raise the event without null check. Do this:
var listChanged = ListChanged; if (listChanged != null) listChanged(this,new ListChangedEventArgs(ListChangedType.ItemChanged, index));
As a side note, if Property1 or Property2 are complex objects, It's recommended to create for them you own equal methods (
Equal
,GetHashCode
,==
and!=
). If the are generic, implementIEquatable<T>
-
\$\begingroup\$ 1. I create a new ListItem, because user don't to be able to hange anything. 2. In project i use Extension methods to raise event. It have a check. 3. It a good idea. \$\endgroup\$Nodon– Nodon2015年12月23日 08:43:12 +00:00Commented Dec 23, 2015 at 8:43
-
1\$\begingroup\$ It'd be helpful to explain why the temporary variable is needed in the null check. I.e. The handler could go null between the check and call without it. \$\endgroup\$RubberDuck– RubberDuck2015年12月23日 09:56:32 +00:00Commented Dec 23, 2015 at 9:56