An abstract property with a type declared in a derived class?

Is it possible to have an abstract property that returns the type defined in the derived class:

abstract class baseClass
{
    public abstract e_Type type { get; }
}

class derived : baseClass
{
    public enum e_Type
    {
        type1,
        type2
    }

    private e_Type _type;
    public e_Type type { get { return _type; } }
}

or should I return an int and display it in a derived class. Any other suggestions are welcome.

+3
source share
2 answers

Of course you can:

abstract class BaseClass<T>
{
    public abstract T Type { get; }
}

class Derived : BaseClass<EType>
{    
    public enum EType
    {
        type1,
        type2
    }

    private EType _type;
    public override EType Type { get { return _type; } }
}

You don't even need to declare it abstract:

class BaseClass<T> {
    private T _type;
    public T Type { get { return _type; } }
}

which can then be used as:

BaseClass<EType> classInst = new BaseClass<EType>();
+5
source

Well, you can explicitly specify a type, but it must be a type, and not just "one called e_Type declared in a particular subclass".

Or you can make it a generic type, of course, as follows:

public abstract class BaseClass<T>
{
    public abstract T Type { get; }
}

public class Derived : BaseClass<EType>
{
    public enum EType
    {
        ...
    }

    private EType type;
    public EType Type { get { return type; } }
}

, , .

+5

Source: https://habr.com/ru/post/1776936/


All Articles