简体   繁体   中英

C# Inheritence Issue with new keyword

I want to override the Body member in a MailMessage class so that it has essentially a Header and Footer.

I've extended the MailMessage class like this;

public class XMessage : MailMessage
{

private string header;
private string footer;
private string xbody;

new public string Body //hides MailMessage.Body
{
 get
  {
    return header + xbody + footer;
  }
}

////.....

}

When passing the XMessage to an SmtpClient 's .Send(MailMessage m) however, the body is blank. MailMessage.Body is not marked for overriding, but how can I get this behaviour from an extended class?

As you are observing, method hiding is not the same as overriding. As SmtpClient.Send(MailMessage m) is expecting a MailMessage it will use the implementation of Body defined in the MailMessage class.

As mentioned by Amy in the comments, this situation would be better suited to composition rather than inheritance.

An example:

public class XMessage
{
    private string header;
    private string footer;
    private string xbody;

    public MailMessage GetMailMessage()
    {
        return new MailMessage
        {
             Body = header + xbody + footer
             // set other properties
        };
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM