The correct way to inherit from an abstract class with dependent interfaces in C #

I have an abstract class for sending and receiving messages.

public abstract class MailClient
{
    public IAuthentication MailAuthentication { get; set; }

    internal MailClient(IAuthentication mailAuthenticaton)
    {
        this.MailAuthentication = mailAuthenticaton;
    }

    public abstract State SendMessage(IMessage message);
    public abstract List<IMessage> GetEmails();
}

I want to create a specific class (say for yahoo mail messages). In this way, I create a yahoo client that inherits from an abstract mail client and uses a YahooMessage object that contains the data for the message to send or receive.

public class YahooClient : MailClient
{
    private YahooConfiguration configuration = new YahooConfiguration();

    public YahooClient (string username, string password) : base(new YahooAuthentication(username, password)) 
    { 
    }

    public override List<YahooMessage> GetMessages()
    {
        //Code for retrieving emails
    }

    public override State SendMessage(YahooMessage message)
    {
        //Code for sending emails
    }
}

YahooMessage implements the IMessage interface and adds several new features specific to Yahoo.

However, I got an error because "SendMessage" and "GetMessages" are not implemented with the correct signature in the Child class (YahooClient). Instead of IMessage, I use YahooMessage, which implements the IMessage interface.

, , . ?

+4
1

, .

public abstract class MailClient<TMessage> where TMessage: IMessage
{
    public IAuthentication MailAuthentication { get; set; }

    internal MailClient(IAuthentication mailAuthenticaton)
    {
        this.MailAuthentication = mailAuthenticaton;
    }

    public abstract State SendMessage(TMessage message);
    public abstract List<TMessage> GetEmails();
}

public class YahooClient : MailClient<YahooMessage>
{
    private YahooConfiguration configuration = new YahooConfiguration();

    public YahooClient (string username, string password) 
        : base(new YahooAuthentication(username, password)) 
    { 
    }

    public override List<YahooMessage> GetMessages()
    {
        //Code for retrieving emails
    }

    public override State SendMessage(YahooMessage message)
    {
        //Code for sending emails
    }
}
+3

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


All Articles