日期:2010-07-28  浏览次数:20578 次

  早闻.NET 2.0中泛型的大名,但一直未在实际开发中使用。

  最近在开发博客园网站程序的过程中体验了一下。

  应用场景:

  在配置文件中通过反序列化读取相应的邮件设置。

  配置文件示例:

<BlogConfigurationSettings>
<MailSettings>
      <MailSetting Name="ApproveEmail" SmtpServer="smtp.126.com" EmailFrom="" UserName="" PassWord=""></MailSetting>
      <MailSetting Name="ContactEmail" SmtpServer="smtp.163.com" EmailFrom="" UserName="" PassWord=""></MailSetting>     
</MailSettings>
</BlogConfigurationSettings>

  功能说明:

    通过该配置文件,反序列化得到BlogConfigurationSettings实例的属性MailSettings,然后根据关键字得到相应的MailSetting,比如:名为ApproveEmail的MailSetting。

MailSetting的定义:

     MailSetting
 [Serializable]
    public class MailSetting
    {
        private string _name;
        [XmlAttribute("Name")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private string _smtpServer;
        [XmlAttribute("SmtpServer")]
        public string SmtpServer
        {
            get { return _smtpServer; }
            set { _smtpServer = value; }
        }

        private string _mailFrom;
        [XmlAttribute("MailFrom")]
        public string MailFrom
        {
            get { return _mailFrom; }
            set { _mailFrom = value; }
        }

        private string _username;
        [XmlAttribute("UserName")]
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }

        private string _password;
        [XmlAttribute("Password")]
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }

        public string Key
        {
            get { return this.Name; }
        }
      
    }

  如果不使用泛型,我们可以通过数组或者集合类来实现。

  对于数组,我们需要在BlogConfigurationSettings进行这样的定义:

private MailSetting [] __mailSettings;
[XmlArray("MailSettings")]
public MailSetting []