为什么不是基于参数类型调用的最具体的方法

Saa*_*aab 9 c# oop polymorphism overloading

总OO noob问题在这里.我在课堂上有这两种方法

private void StoreSessionSpecific(LateSession dbSession, SessionViewModel session)
{
    session.LateSessionViewModel.Guidelines = dbSession.Guidelines.ToList();
}

private void StoreSessionSpecific(Session dbSession, SessionViewModel session )
{
        // nothing to do yet...
}
Run Code Online (Sandbox Code Playgroud)

当我调用StoreSessionSpecific时,dbSession的类型为LateSession(LateSession继承Session)

var dbSession = new LateSession();
StoreSessionSpecific(dbSession, session);
Run Code Online (Sandbox Code Playgroud)

我期待最高的一个被召唤.由于dbSession属于LateSession类型.

@Paolo Tedesco这是类的定义方式.

public class Session
{
    public int ID { get; set; }
    public int SessionTypeId { get; set; }
    public virtual SessionType SessionType { get; set; }
    [Required]
    public DateTime StartTime { get; set; }
    [Required]
    public DateTime EndTime { get; set; }
    // Session duration in minutes
    // public int SessionDuration { get; set; }
    public virtual ICollection<Attendee> Attendees { get; set; }

}

public class LateSession : Session
{


    public int MaxCriticalIncidentsPerUser { get; set; }
    public int MaxResultCriticalIncidents { get; set; }

    public virtual ICollection<Guideline> Guidelines { get; set; }


}
Run Code Online (Sandbox Code Playgroud)

Ang*_*ere 7

嗯,你的假设是合理的,有些语言可以像你想象的那样工作.

那么你的代码看起来像这样:

Session s = new LateSession(); // the compiler only "knows" that s is of type Session
StoreSessionSpecific(s);
Run Code Online (Sandbox Code Playgroud)

或者看起来像这样:

LateSession ls = new LateSession(); // the compiler knows that ls is in fact a LateSession
StoreSessionSpecific(ls);
Run Code Online (Sandbox Code Playgroud)

在第一个例子中,编译器预先不知道"s"的实际类型是什么,并且硬编码使用Session参数调用方法.在第二个示例中,编译器同样生成对另一个方法的硬编码调用.

在其他语言中,方法调用是"动态的",这意味着在运行时期间会考虑实际类型.对其参数进行多态化的方法称为"多方法"(它们不仅在它们定义的类中具有多态性,而且在参数上也是多态的,因此"多")(编辑:固定拼写错误)

  • 但实际上,在这种情况下,事情**应该按预期工作,因为类型在编译时是已知的,并且应该调用正确的重载.可能还有一些其他问题,从显示的例子中看不出来...... (2认同)