Reputation: 193302
I have a number of plural item classes which each have a collection of singular item classes, like this:
public class Contracts : Items
{
public List<Contract> _collection = new List<Contract>();
public List<Contract> Collection
{
get
{
return _collection;
}
}
}
public class Customers: Items
{
public List<Customer> _collection = new List<Customer>();
public List<Customer> Collection
{
get
{
return _collection;
}
}
}
public class Employees: Items
{
public List<Employee> _collection = new List<Employee>();
public List<Employee> Collection
{
get
{
return _collection;
}
}
}
I can imagine I could use generics to put this up into the parent class. How could I do this, I imagine it would look something like this:
PSEUDO-CODE:
public class Items
{
public List<T> _collection = new List<T>();
public List<T> Collection
{
get
{
return _collection;
}
}
}
Upvotes: 1
Views: 141
Reputation: 22149
Yes, although Items would have to be generic as well.
public class Items<TItem>
{
private IList<TItem> _items = new List<TItem>();
public IList<TItem> Collection
{
get { return _items; }
}
// ...
}
It would probably make sense to have Items inherit from IEnumerable<TItem>
too.
Upvotes: 5
Reputation: 284796
That's completely right, except you also want a <T>
after Items:
public class Items<T>
{
public List<T> _collection = new List<T>();
public List<T> Collection
{
get
{
return _collection;
}
}
}
To instantiate:
Items<Contract> contractItems = new Items<Contract>();
Upvotes: 6