简体   繁体   English

从具有抽象属性的泛型类继承

[英]Inheritance from generic class with abstract property

I'm trying to have a class inherit from an abstract class with a generic property in it. 我试图让一个类从一个具有通用属性的抽象类继承。 I think I'm missing something real important. 我想我缺少真正重要的东西。 The only way I can get rid of this error is getting rid of the constructor in the base class. 我摆脱这种错误的唯一方法是摆脱基类中的构造函数。 But if I do that then my class would lack of purpose. 但是,如果我那样做,那么我的班级就会缺乏目标。

Error 错误

Error CS7036 There is no argument given that corresponds to the required formal parameter 'propA'... 错误CS7036没有给出与所需形式参数'propA'相对应的参数...

Base Class 基类

public abstract class BaseClass<T> where T:class
{
    public string propA{ get; set; }
    public int propB{ get; set; }
    public IEnumerable<T> propC { get; set; }

    public BaseClass(string propA, int propB, IEnumerable<T> propC)
    {
        this.propA = propA;
        this.propB = spropB; 
        this.propC = propC;
    }

    public abstract IEnumerable<T> Method1();

    public abstract string Method2();

    public abstract void Method3();
}

Derived Class 派生类

public class DerivedClass: BaseClass<SomeClass> 
{
    public override IEnumerable<SomeClass> Method1()
    {
        //Code Here
    }

    public override string GetDefaultSortField()
    {
         //Code Here
    }

    public override void SetSortParams()
    {
         //Code Here
    }
}

You do not have an explicit constructor in your derived class, so it 'inherits' the constructor of the base class. 您的派生类中没有显式的构造函数,因此它“继承”了基类的构造函数。 But the base class constructor has a parameter that uses a generic type T, which is not defined in the derived class. 但是基类构造函数具有一个使用泛型T的参数,该类型未在派生类中定义。 If you add a constructor explicitly to the derived class, it should be fine. 如果将构造函数显式添加到派生类,则应该没问题。 I mean like this: 我的意思是这样的:

    public DerivedClass(string propA, int propB, IEnumerable<SomeClass> propC)
        : base(propA, propB, propC)
    {
    } 

Note that this way the IEnumerable<SomeClass> becomes IEnumerable<T> in the base class, as the generic type parameter T is bound to SomeClass in DerivedClass . 请注意,由于通用类型参数T绑定到DerivedClass SomeClassDerivedClass IEnumerable<SomeClass>在基类中成为IEnumerable<T>

You've missed the constructor in the DerivedClass . 您已经错过了DerivedClassconstructor DerivedClass But since the default constructor in the base class contains three parameters you need to call the matching base constructor. 但是,由于基类中的默认构造函数包含三个参数,因此您需要调用匹配的基本构造函数。 So add this constructor to the DerivedClass and it will solve your issue: 因此,将此构造函数添加到DerivedClass ,它将解决您的问题:

public DerivedClass(string propA, int propB, IEnumerable<SomeClass> propC) 
      : base(propA, propB, propC)
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM