Edw*_*uay 1 c# generics inheritance
我有许多复数项目类,每个类都有一个单一项目类的集合,如下所示:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以想象我可以使用泛型将它放到父类中.我怎么能这样做,我想它看起来像这样:
伪代码:
public class Items
{
public List<T> _collection = new List<T>();
public List<T> Collection
{
get
{
return _collection;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是完全正确的,除了你还想要一个<T>后项目:
public class Items<T>
{
public List<T> _collection = new List<T>();
public List<T> Collection
{
get
{
return _collection;
}
}
}
Run Code Online (Sandbox Code Playgroud)
要实例化:
Items<Contract> contractItems = new Items<Contract>();
Run Code Online (Sandbox Code Playgroud)
是的,虽然物品也必须是通用的.
public class Items<TItem>
{
private IList<TItem> _items = new List<TItem>();
public IList<TItem> Collection
{
get { return _items; }
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
让Items继承也许是有意义的IEnumerable<TItem>.