问题继承时抽象泛型类

问题描述:

我有一个抽象的泛型类:问题继承时抽象泛型类

public abstract class A<T> where T : class, new(){ 

    public A (IEnumberable<T>_Data){ 
     this.Data = _Data; 
    } 

    private IEnumerable<T>_data; 
    public IEnumerable<T> Data{ 
     get { return _data; } 
     set { _data = value;} 
    } 

} 

后来,当我继承类:

public class B<T> : A<T> where T : class, new(){ 

} 

我得到一个错误说:

There is not argument that corresponds to the required formal parameter '_Data' of 'A<T>.A(IEnumerable<T>)' 
in the 'B' class. 
+2

什么是'公共A(_Data)'让你的基类构造函数的调用?这不会编译! – user3185569

+0

这是一个构造函数 –

+0

是的,我用手在这里输入了代码。这是一个输入错误。 无论如何解决了它 –

您需要继承A<T>,而不是A

public class B<T> : A<T> where T : class, new(){ 

} 

此外public A(_Data)不是构造函数,我假设你想要。您需要改为public A<T>(IEnumerable<T> _Data)

最后但并非最不重要的是,您必须为B创建一个构造函数,它可以调用A中的任何构造函数。因此,要么定义A一个无参数的构造函数或一个在BIEnumerable<T>作为参数:

public class B<T> : A<T> where T : class, new() 
{ 
    public B<T>(IEnumerable<T> data) : base(data) { ... } 
} 
+0

我原来的代码有点复杂,所以我在这里手工输入。 我确实继承了A

+1

然后确保在发布此问题前提供可验证的示例。或者适当地编辑它。 – HimBromBeere

由于在错误说,它不能创建的基类,因为你没有提供B.正确的构造改变如果你想通过任何参数

public class B<T> : A<T> where T : class, new(){ 
    public B(IEnumerable<T> data):base(data) { 
    } 
} 

否则,在构造函数中新建你的数据并将其传递给base。

无论是在你的基类或其他提供公共参数构造函数,建议通过传递IEnumberable<T>从派生类