General way to format an object as an object and body?

I am trying to take a list of objects and format them as the subject and body of the letter. To illustrate what I'm doing, do the following examples:

public string GetSubject(Person myPerson) 
{ 
    return String.Format("To {0}", myPerson.Name); 
}

public string GetMessage(Person myPerson) 
{ 
    return String.Format("Dear {0}, Your new salary: {1}", 
        myPerson.Name, myPerson.Salary); 
}

public string GetSubject(VacationDay dayOff) 
{ 
    return String.Format("Vacation reminder!"); 
}

public string GetMessage(VacationDay dayOff) 
{ 
    return String.Format("Reminder: this {0} is a vacation day!", dayOff.Name); 
}

Later I have a bunch of letters that I want to send to the package:

// myEmailObjects is a "List<object>"
foreach (var emailItem in myEmailObjects)
{
    SendEmail(from, to, GetSubject(emailItem), GetMessage(emailItem));
}

The problem is that this code does not compile, because the compiler cannot decide GetSubjectwhich routine to GetMessagecall and which routine . Is there a general way to write this without using an operator isor asaround the place for type checking?

+4
source share
2 answers

. , , , . GetSubject() GetMessage() - , :

public interface IEmailable {
    string GetSubject();
    string GetMessage();
}

, :

public class VacationDay : IEmailable

List<IEmailable>(), .

+7

, , List<object>, , , .

foreach (var emailItem in myEmailObjects)
{
    if (emailItem is Person)
    {
        SendEmail(from, to, GetSubject((Person)emailItem), 
            GetMessage((Person)emailItem));
    }
    else if (emailItem is VacationDay)
    {
        SendEmail(from, to, GetSubject((VacationDay)emailItem), 
            GetMessage((VacationDay)emailItem));
    }

}

( , , ) ( ).

+1

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


All Articles