我有一个通用 Controller ,我将一个只包含属性的类传递给它。一切都很好,但是......
我想在 Controller 类中创建另一个类来继承传递的类。
有点像这样:
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
}
}
}
如何使用继承的 T 创建类 Recordset?
最佳答案
编译器 won't let you do that (我确定错误消息已告诉您):
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.
你可以使用组合而不是继承:
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();
}
}
}
关于c# - 从类型参数创建继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36853070/