When do we really need to call the parent overridden method from the main method?

When do we really need to call the parent overridden method from the override method of the child?

namespace MvcMovie.Models
{
    public class MovieInitializer: DropCreateDatabaseIfModelChanges<MovieDbContext>
    {
        protected override void Seed(MovieDbContext context)
        {
            base.Seed(context);// is it necessary to invoke this parent method here?
        }
    }
}
+3
source share
5 answers

The dumb answer is "you never know when to call a base class method."

You can also ask a question about the order in which the base class method should be called? as in, before or after the implementation of the derived class!

I asked a similar question, look here .

, , . , API . , , ( ) ( ), . API.

, .

+3

CLR. , , .

+4

,

: Child 1 A, B C , , Child 2 X, Y Z.

public class Parent
{
    protected IList<string> Names {get;set;}
    public virtual void Addnames()
    {
         Names = new List<string>(){"A", "B"};
    }
}

public class Child1 : Parent
{
    public override void Addnames()
    {
         base.Addnames();
         Names.Add("C");
    }
}

public class Child2 : Parent
{
    public override void Addnames()
    {
         Names = new List<string>(){"X", "Y", "Z"};
    }
}

, , , . ,

+1

, , .

, , , Collection<T>, , .

public class Dinosaurs : Collection<string>
{
    public event EventHandler<DinosaursChangedEventArgs> Changed;

    protected override void InsertItem(int index, string newItem)
    {
        base.InsertItem(index, newItem);

        EventHandler<DinosaursChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new DinosaursChangedEventArgs(
                ChangeType.Added, newItem, null));
        }
    }

    ...
}

+1

-, , .

- . , , .

If you implement methods that must have a common signature for different classes, but without the usual behavior, you must implement an interface.

EDIT: To clarify, the base method should always do the part of the work that all derived classes should do. Derived classes should only ADD to this behavior.

+1
source

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


All Articles