Sometimes I have to do a lot of typechecking to determine what to do
based on the type of an object that looks like this:
(Node is an abstract base class)
void Process(Node node) {
if (node is BinaryNode) {
BinaryNode bnode = (BinaryNode)node;
Process(bnode.Left);
Process(bnode.Right);
}
else if (node is SetNode) {
SetNode snode = (SetNode)node;
foreach (Node n in snode.Nodes) {
Process(n);
}
}
else if (...) {
...
}
}
Now to avoid multiple class casts you would use the "as" statement, and
the example would be like this:
void Process(Node node) {
BinaryNode bnode = node as BinaryNode;
if (bnode != null) {
Process(bnode.Left);
Process(bnode.Right);
}
else {
SetNode snode = node as SetNode;
if (snode != null) {
foreach (Node n in snode.Nodes) {
Process(n);
}
}
else {
...
}
}
}
My problem is when you have a lot of subclasses to Node that you want to
process in different ways the second example gets very deeply nested and
hard to maintain. Is there a better way to deal with multiple downcasts
like this?
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com