c# - 从类型参数创建继承类

标签 c# class generics inheritance

我有一个通用 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/

相关文章:

c# - 通用类型转换失败

Java泛型问题,修改约束?

c# - 序列化包含 StateServer 的 linq2sql 对象的对象

c# - 如何从 Windows XP 下的程序中知道或更改 Windows 事件日志的大小?

c# - C#中的目录遍历

c++ - 如何将时间返回为 DD :HH:MM:SS?

带有通配符的Java泛型问题

c# - 在没有集成服务的情况下从文本文件批量插入到 sql server 的最快方法

C++尝试按平均值对类数组进行排序,然后按递增顺序对它们进行排序

python - 类实例实现,初始化实例——来自SICP python