"Simon" <si****************@nodomain.com> a écrit dans le message de news:
un**************@TK2MSFTNGP11.phx.gbl...
| An instance of the collection will contain various instances of the two
| derived types and in the future many more derived types. At various
| times I need to iterate through each item setting various values.
|
| I can see a problem in that I still need to test within an iteration
| routine the actual type of each instance, which to me sort of defeats
| the reason for deriving from a base class in the first place.
You need to look at the Visitor design pattern. It is intended to add
functionality to a hierarchy of classes without altering the code of the
clesses themselves. It also allows you to execute different code, depending
on the type of the item being visited.
public interface IVisitor
{
}
public interface IVisitable
{
void Accept(IVisitor visitor);
}
public class MyHierarchyVisitor : IVisitor
{
public MyHierarchyVisitor(...)
{
// pass parameters to internal fields for external objects that will be
used
// whilst visiting nodes in a list.
}
void VisitDerivedTypeA(DerivedTypeA node)
{
// do something specific to a DerivedTypeA object
}
void VisitDerivedTypeB(DerivedTypeB node)
{
// do something specific to a DerivedTypeB object
}
}
public abstract class BaseType : IVisitable
{
...
public abstract void Accept(IVisitor visitor);
}
public class DerivedTypeA : BaseType
{
...
public override void Accept(IVisitor visitor)
{
if (visitor is MyHierarchyVisitor)
((MyHierarchyVisitor) visitor).VisitDerivedTypeA(this);
}
}
public class DerivedTypeB : BaseType
{
...
public override void Accept(IVisitor visitor)
{
if (visitor is MyHierarchyVisitor)
((MyHierarchyVisitor) visitor).VisitDerivedTypeB(this);
}
}
Then you treat your list like this :
{
List<BaseType> items...
// add items to list
MyHierarchyVisitor visitor = new MyHierarchyVisitor(...);
foreach (IVisitable node in items)
node.Accept(visitor as IVisitor);
}
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer