This article is about some inconspicuous programming tips.
I,
In the past, I wrote the following code:
public List<IMessageDataGroup> DataGroups { get; set; }
It is equivalent:
private List<IMessageDataGroup> _dataGroups = null;public List<IMessageDataGroup> DataGroups{get { return this._dataGroups; }set { this._dataGroups = value; }}
Therefore, each time you call this rule set attribute, you must determine whether it is empty:
if (messageCustomizeMode.DataGroups == null || messageCustomizeMode.DataGroups.Count == 0){ // TODO}else{ // TODO}
It's really annoying.
II,
Then, I will define the role roups attribute as follows:
private List<IMessageDataGroup> _dataGroups = null;public List<IMessageDataGroup> DataGroups{ get { if (this._dataGroups == null) { this._dataGroups = new List<IMessageDataGroup>(); } return this._dataGroups; }}
In this way, I don't have to worry about the empty rolling roups attribute:
if (messageCustomizeMode.DataGroups.Count == 0){ // TODO}else{ // TODO}
However, I encountered a little trouble in assigning values to this attribute.
Previously, I could do this:
messageCustomizeMode.DataGroups = currentDataGroups;
Now, I can only do this:
messageCustomizeMode.DataGroups.Clear();foreach (IMessageDataGroup item in currentDataGroups){ messageCustomizeMode.DataGroups.Add(item);}
Iii. Final solution
Finally, I decided to define the volume roups attribute as follows:
private List<IMessageDataGroup> _dataGroups = null;public List<IMessageDataGroup> DataGroups{ get { if (this._dataGroups == null) { this._dataGroups = new List<IMessageDataGroup>(); } return this._dataGroups; } set { if (value != this._dataGroups) { if (this._dataGroups != null) { this._dataGroups.Clear(); } this._dataGroups = value; } }}
In this way, first, I will never worry about it being empty when I reference the volume roups attribute later. Second, I can assign values directly as before.
Boring tips.