Derived method stronger than override in c#?

你说的曾经没有我的故事 提交于 2019-12-05 15:18:12

There are two concepts here which are being confused, overloading and overriding. Overloading is the concept of having multiple signatures for a function of the same name and choosing one to call based on that signature. Overriding is the concept of re-defining a method in a derived class.

Whether or not the child class overrode one of the method definitions does not matter at all to which function will be called because it does not change the signature of either method. By definition and construction overriding a method cannot change it's signature.

So, if the signature is unchanged exactly the same mechanics for determining the correct function to call based on the signature will be used against both the parent and child classes.

Update

In fact there is a little bit more to it as Eric Lippert points out in his blog. It turns out in fact that if there is a method that matches the overload in the child class it will not look for any methods in base classes. The reasons are sane - avoiding breaking changes - but the result is somewhat illogical when you own both the base and child class.

I can only echo Jon Skeet: "Given this oddness, my advice would be to avoid overloading across inheritance boundaries... at least with methods where more than one method could be applicable for a given call if you flattened the hierarchy"

That's because your child takes an object.

public class Child : Base
{
    public override void Foo(object strings)  { "4".Dump();}
}

Make it string and then child one will be called.

public class Child : Base
{
    public override void Foo(string strings)  { "4".Dump();}
}

Why this?

Because compiler sees that child has object prameter it has to convert to string while in base class it is readily available as string.

So it calls base one.

Though Overridden function is nearer in the child class. But here rules are different in child and base. Child has object and base has string. It was fair if both had object or both had string.

I read this in Jon Skeet's C# in Depth Overloading Section

You see here best match rule .

You pass a string like an argument to a Foo(..) function.

Base class has a Foo(string..), Child class, instead, has not. So the method of base is picked eventually , in this case.

I think here the base class method is chosen based on its dataType

As c.Foo("d"); matches exactly to the base class method and there is not any method overridden for it in the derived class therefore the base class method is called.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!