如何将此字典重构为类
本文关键字:重构 字典 | 更新日期: 2023-09-27 18:36:43
我觉得这个词典包含的信息太多了:它包含构建一个电子邮件路径,它包含额外的参数来获取电子邮件模板所需的其他数据。这是我的示例程序的简化版本:
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
}
}
我应该考虑其他因素吗?
你当然是对的 - 你所拥有的需要重构。也许阅读标准的面向对象原则会有所帮助。我会有更多类似的东西,尽管我需要更多地了解您打算如何使用它(公共设置器可能是可取的):
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();
这绝对是在滥用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
对象作为参数。
从这一点来看,我也可能会为Action
和TemplateName
制作enum
。
public enum Action
{
Update,
}
public enum Template
{
TemplateX,
}
然后你的财产将是
public Action EmailAction {get;set;}
public Template TemplateName {get;set;}