0

我觉得这个字典包含太多信息:它包含构建电子邮件路径的信息,它包含额外的参数来获取电子邮件模板所需的其他数据。这是我的示例程序的简化版本:

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
    }

}

还有其他我应该考虑的重构因素吗?

4

2 回答 2

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();
于 2013-10-24T02:56:26.400 回答
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对象作为参数。

从这一点来看,我也可能会为and制作enum's 。ActionTemplateName

public enum Action
{
    Update,
}
public enum Template
{
    TemplateX,
}

然后你的属性将是

public Action EmailAction {get;set;}
public Template TemplateName {get;set;}
于 2013-10-24T03:00:32.300 回答