简体   繁体   中英

C# constructor for type parameterized abstract class

So I found a lot of answer to the question if and why it is ok to have a constructor defined in an abstract class.

I am currently trying to make a parameterized constructor available in an abstract class which has a type parameter:

public abstract class Cell<T>
{
    int address;
    T value;

    protected Cell<T>(int address, T value)
    {

    }
}

But c# simply refuses it and Intellisense completely breaks down. So why is it possible to have a constructor in an abstract class but as soon as the abstract class gets a type parameter everything refuses it?

Remove <T> from the constructor declaration and then everything will work. For example, this compiles just fine:

public abstract class Cell<T>
{
    int address;
    T value;

    protected Cell(int address, T value)
    {

    }
}

public class CellInt : Cell<int>
{
    public CellInt(int address, int value): base(address, value) { }
}

Your constructor should look like this:

protected Cell(int address, T value)
{

}

You don't need to specify the type parameter in the constructor.

The point of a constructor in an abstract class is to force derived classes to call one of the abstract class' constructors from any constructor that the derived classes define.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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