问题
I have a lot of XML nodes generated by a 3rd party:
<node id='8440' name='nodeOne' property_two='7.22' sorting_index='20'/>
<node id='8440' name='nodeTwo' property_two='7.22' sorting_index='subItemThree;30;subItemTwenty;50'/>
...
Every attribute has the same type and meaning among all nodes except one named sorting_index. Usually, it contains an int
indicating, well, object's sorting index. In the first node above sorting index is 20 for an object named "nodeOne".
Unfortunately, sometimes those nodes are just "carriers" of a sorting index for multiple subobjects. Looking into a second node given above, we can see that it provides sorting indeces for objects named "subItemThree" and "subItemTwenty" with values 30 and 50 respectively.
Im my approach, I created two classes with first being a representation of a node with simple sorting_index and second class being a representation of a node with the complicated sorting_index logic. Second class extended the first one and added a method to extract an array of sorting indeces from SortingIndex property's getter.
So what I did is I parsed everything to a base class (SortingIndex property is of string
type) and then converted some of them to a derived class. I've described the logic behind this in another question: Converting from base to derived object while having a huge constructor definition
However, I was told that having such a conversion is not a good design approach. What are your suggestions? I feel like having 2 totally independent classes with absolutely same logic except for one property is an overkill.
回答1:
Whether one should inherit from the other you should consider whether the derived class is substitutable for the base class, see the Liskov substitution principle
If its not, you could try something like this with a common base class that has all the properties apart from the sort index.
public abstract class BaseClass
{
public string Property1 { get; }
public int Property2 { get; }
public BaseClass(string prop1, int prop2)
{
...
}
}
public class StringClass : BaseClass
{
public int SortIndex { get; }
public StringClass(string prop1, int prop2, int index) :
base(prop1, prop2)
{
SortIndex = index;
}
}
public class CollectionClass : BaseClass
{
public Dictionary<string, int> SortIndexes { get;}
public CollectionClass(string prop1, int prop2, Dictionary<string, int> indexes) :
base(prop1, prop2)
{
SortIndexes = indexes;
}
}
来源:https://stackoverflow.com/questions/53060487/parsing-xml-object-to-multiple-classes-with-different-logic