我觉得这个词典中包含的信息太多了:它掌握了建立一个信息的信息 电子邮件路径,它包含额外的参数,以获取电子邮件模板所需的其他数据。以下是我的示例程序的简化版本:
void Main()
{
//Sample Path = Root/Action/TemplateX.txt
//Date used in other method
Dictionary<string,object> emailDict = new Dictionary<string,object>
{
{"Root","Email"},
{"Action", "Update"},
{"TemplateName", "TemplateX.txt"},
{"Date", DateTime.Now},
};
//Create email object
Email email = new Email();
//Send e-mail with email dictionary
email.SendEmail(emailDict);
}
// Define other methods and classes here
public class Email
{
public void SendEmail(Dictionary<string,object> emailDict)
{
//Build path from emailDict and use parameters from emailDict
//Send E-mail
}
}
我还应该考虑其他因素吗?
答案 0 :(得分:3)
你当然是对的 - 你需要重构的东西。也许阅读标准的面向对象的主体会有所帮助。我会有更多这样的东西,虽然我需要更多地了解你打算如何使用它(公共制定者可能是可取的):
enum EmailAction { Update } // add any other possible actions
public class Email
{
public string Email { get; private set; }
public EmailAction EmailAction { get; private set; }
public string TemlateName { get; private set; }
public DateTime DateTime { get; private set; }
public Email(string email, EmailAction action, string templateName, DateTime dateTime)
{
this.Email = email;
this.EmailAction = action;
this.TemlateName = templateName;
this.DateTime = dateTime;
}
public void Send()
{
//Build path from properties on this instance of Email
}
}
然后你可以去:
Email newEmail = new Email("Email", EmailAction.Update, "TemplateX.txt", DateTime.Now);
newEmail.Send();
答案 1 :(得分:2)
这肯定会滥用Dictionary
。如果您的值为object
,那么您将失去所有类型的安全性,这使您可以处理InvalidCast
个例外以及其他一系列问题。只需将所有值都提取到类中的属性中:
public class EmailFields
{
public string Root {get;set;}
public string Action {get;set;}
public string TemplateName {get;set;}
public DateTime Date {get;set;}
public EmailHelper
{
Date = DateTime.Now;
}
}
您的SendEmail
方法会将EmailFields
对象作为参数。
从这一点开始,我也可能会enum
和Action
TemplateName
。{/ p>
public enum Action
{
Update,
}
public enum Template
{
TemplateX,
}
然后您的属性将
public Action EmailAction {get;set;}
public Template TemplateName {get;set;}