dre*_*w_w 4 c# casting strong-typing
我正在尝试获取对象列表并将其格式化为电子邮件主题和正文.为了说明我在做什么,请参考以下示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
后来我收到了一堆我想要批量发送的电子邮件:
// myEmailObjects is a "List<object>"
foreach (var emailItem in myEmailObjects)
{
SendEmail(from, to, GetSubject(emailItem), GetMessage(emailItem));
}
Run Code Online (Sandbox Code Playgroud)
问题是此代码无法编译,因为编译器无法解析调用哪个GetSubject和哪个GetMessage例程.是否有任何通用的方法来编写它而不使用is或as运算符来检查类型?
这就是为什么建立接口.从概念上讲,接口就像一个合同,类可以在必须定义接口指定的方法的地方签名.将每个GetSubject()和GetMessage()方法定义为相应类的成员方法,然后创建以下接口:
public interface IEmailable {
string GetSubject();
string GetMessage();
}
Run Code Online (Sandbox Code Playgroud)
然后,使所有涉及的类实现接口:
public class VacationDay : IEmailable
Run Code Online (Sandbox Code Playgroud)
您现在可以创建一个List<IEmailable>(),并且可以在其元素上调用这两个方法.