"Brett Romero" <ac*****@cygen.com> a écrit dans le message de news:
11**********************@75g2000cwc.googlegroups.c om...
Let me clarify a little more. I want to call MyClass.Add() vs
MyClass.List.Add(). If I don't inherit, the List's Add, Remove, Count,
etc need to be encapsulated. This means I to have create all of those
methods. Inheritance avoids that.
As Jon says, you are really overusing inheritance here.
Assuming you want to include an internal list in a class, then you don't
want to go to the expense of inheriting a generic list just to include the
derived class, which is identical in behaviour to the class from which it
derives.
I take it you want something like this
publlic class Employee
{
...
}
public class Company
{
private string name;
private Address address;
...
private List<Employee> employees = new List<Employee>();
// public properties, etc
}
This then means that you would call :
{
aCompany.Employees.Add(...)
}
Which makes more sense than deriving Company from List<Employee>, as a
Company could also have other lists of things like Customers, etc.
This way of allowing access to the list itself, is known as Aggregation and
it assumes that the list of objects is not "owned" by the containing object.
IOW, the people that we can call Employees are not created by the Company,
they have a life outside of the Company.
OTOH, if you want to model something like a SalesOrder, then you would
encapsulate the list, hiding its own methods, thus preventing unauthorised
use of the list.
public class ReadOnlyList<T> : IEnumerable<T>
{
public T this[int index] { get {...} }
public int Count { get {...} }
IEnumerator<T> IEnumerable<T>.GetEnumerator() { get {...} }
private List<T> list;
public ReadOnlyList(List<T> list)
{
this.list = list;
}
}
This is a readonly list wrapper class that allows examination of the items
in a list but not manipulation of the list itself. It is a wrapper class.
public class SalesOrder
{
public class Line
{
...
internal Line() // only accessible in business class assembly
{
...
}
}
private List<Line> lines = new List<Line>();
public ReadOnlyList<Line> Lines
{
get { return new ReadOnlyList<Line>(lines); }
}
public Line AddLine()
{
Line result = new Line();
lines.Add(result);
return result;
}
}
Now the Lines property returns a read-only list for examination and
alteration of the items only.
Adding a Line is only possible by asking the SalesOrder to create one and
then return it for editing.
This way of preventing list operations whilst allowing operations on the
items, is known as Composition.
Does that help or confuse ? :-)
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer