Unable to override base property

The following code is bad code. Please help me achieve what I am trying to achieve, but with good code. I want to have an array of objects that is retrieved from the database. I want to be able to use this array in BaseClass when running DoStuff (). I know that I cannot lose heart, this is not what I am looking for here. I just want to be able to set fields in a derived class and use fields in the DoStuff () database.

public class BaseObject
{

}

public class DerivedObject : BaseObject
{

}

public class BaseClass
{
    public BaseObject[] Objects;

    public virtual void DoStuff()
    {
        // use the Objects
    }
}

public class DerivedClass : BaseClass
{
    public override DerivedObject[] Objects;

    public override void DoStuff()
    {
        // Do stuff unique to the derived.

        base.DoStuff();
    }
}
+3
source share
2 answers

Are you looking for generics?

public class BaseClass<T>
where T : BaseObject
{
    public T[] Objects;

    public virtual void DoStuff()
    {
        // use the Objects
    }
}

public class DerivedClass : BaseClass<DerivedObject>
{
    public override void DoStuff()
    {
        // Do stuff unique to the derived.

        base.DoStuff();
    }
}

T ( ), T BaseObject , BaseObject, DerivedClass DerivedObject T, DerivedClass Objects DerivedObject[].

+9

,

public class BaseClass
{
    public virtual BaseObject[] Objects {get; set;}

    public virtual void DoStuff()
    {
        // use the Objects
    }
}

public class DerivedClass : BaseClass
{
    public override BaseObject[] Objects {get; set;}

    public override void DoStuff()
    {
        // Do stuff unique to the derived.

        base.DoStuff();
    }
}

, .

0

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


All Articles