Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c# - Method overloading and inheritance

I have the following classes:

public class BaseRepository
{
    public virtual void Delete(int id)
    {
        Console.WriteLine("Delete by id in BaseRepository");
    }
}

public class EFRepository: BaseRepository
{
    public override void Delete(int id)
    {
        Console.WriteLine("Delete by Id in EFRepository");
    }

    public void Delete(object entity)
    {
        Console.WriteLine("Delete by entity in EFRepository");
    }
}

Then I use it like:

var repository = new EFRepository();
int id = 1;
repository.Delete(id);

Why in that case only EFRepository.Delete(object entity) will call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically, the way method invocation works in C# is that the compiler looks at the most derived class first, and sees whether any newly declared methods (not including overrides) are applicable for the arguments for the call. If there's at least one applicable method, overload resolution works out which is the best one. If there isn't, it tries the base class, and so on.

I agree this is surprising - it's an attempt to counter the "brittle base class" issue, but I would personally prefer that any overridden methods were included in the candidate set.

Method invocation is described in section 7.6.5.1 of the C# 5 specification. The relevant parts here is:

  • The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F in the set, where C is the type in which the method F is declared, all methods declared in a base type of C are removed from the set. Furthermore, if C is a class type other than object, all methods declared in an interface type are removed from the set. (This latter rule only has affect when the method group was the result of a member lookup on a type parameter having an effective base class other than object and a non-empty effective interface set.)

And in the member lookup part of 7.4, override methods are explicitly removed:

Members that include an override modifier are excluded from the set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...