jeudi 3 septembre 2020

Is there a way to force abstract classes to require the implementation of a constructor with certain parameters?

I have a class called CompObj that I have currently defined as such:

public abstract class CompObj
{
    //Self Contract : Contains both a default and a (string, char, int) constructor.

    public string Write()
    {
        return this.Write(',' , 1);
    }

    public abstract string Write(char d, int currInt);
}

The reason why I need this is because elsewhere I use reflection as such, after checking typeof(T).IsSubclassOf(typeof(CompObj)) in an if-else statement:

ConstructorInfo StrReadr = typeof(T).GetConstructor(new Type[] { typeof(string), typeof(char), typeof(int)});

and

ConstructorInfo DefaultConstructor = typeof(T).GetConstructor(new Type[] { });

This works absolutely fine for my purposes since I work alone and I know that I need to implement this code in order to work. However, I would like to force my future self or any other people who create derivative classes to be required to implement the necessary constructors, preferably at compile time. I have found no way of forcing this. Is it possible?

Thank you!





Aucun commentaire:

Enregistrer un commentaire