Reputation: 788
I have a generic controller to which I pass a class containing only properties. It all works great but...
I want to create another class in the Controller class that inherits the passed class.
Sort of like this:
public class Products
{
public Int32 ProductID {get; set;}
public String ProductName {get; set;}
}
public class ProductController : Controller<Products>
{
public ProductsController() : base("Products", "ProductID", "table", "dbo")
{
}
}
public class Controller<T> : IDisposable where T : new()
{
protected Controller(String tablename, String keyname, String entitytype, String tableschema = "dbo")
{
...
}
//How do I create the Recordset class inheriting T
public class Recordset : T //<----This is what I don't know how to do
{
public Int32 myprop {get; set;}
public void MoveNext()
{
//do stuff
}
}
}
How do I create the class Recordset using T as inherited?
Upvotes: 4
Views: 1829
Reputation: 103447
The compiler won't let you do that (as I'm sure the error message told you):
Cannot derive from 'identifier' because it is a type parameter
Base classes or interfaces for generic classes cannot be specified by a type parameter. Derive from a specific class or interface, or a specific generic class instead, or include the unknown type as a member.
You could use composition instead of inheritance:
public class Controller<T> : IDisposable where T : new()
{
public class RecordSet
{
private T Records;
public RecordSet(T records)
{
Records = records;
}
public void MoveNext()
{
// pass through to encapsulated instance
Records.MoveNext();
}
}
}
Upvotes: 6
Reputation: 788
public class Controller<T> : IDisposable where T : class, new()
{
protected Controller(String tablename, String keyname, String entitytype, String tableschema = "dbo")
{
...
}
public class Recordset<TT> where TT : class, new()
{
public TT myinheritedclass {get; set}
public Int32 myprop {get; set;}
public void MoveNext()
{
//do stuff
}
}
public Recordset<T> myRecordset = new Recordset<T>()
}
Upvotes: -1
Reputation: 995
You can do that using classes under Reflection.Emit namespace. but if you are digging that far youll probably find out you dont need inheritence.
Upvotes: 1