繁体   English   中英

在C#中设置ICollection属性的值

[英]Setting the Value of an ICollection Property in C#

我的类继承了一个接口,所以我需要在Person类中拥有emailaddress属性。

我的问题是获得房产和设置房产的最佳方式是什么

public class Contact : IPerson, ILocation
{
  ...
  [MaxLength(256)]
  public string EmailAddress { 
  get{
    return this.Emails.First().ToString();
  } 
  set{ ????  }
  }
  ....

  public virtual ICollection<Emails> Emails { get; set; }
}

从本质上讲,我试图让课程允许多个电子邮件。

对于完全披露,我对此很新,我可能不会问正确的问题,但我已经搜索了一天半,并没有看到这样的事情(不是我认为这是不寻常的)并且可以使用洞察力。

电子邮件类属性:

[Key]
public int Id { get; set; }

[MaxLength(256)]
    public string EmailAddress { get; set; }

您是否可以控制强制您实施EmailAddressIPerson界面的设计? 如果是这样,我建议重新考虑设计,以避免在同一对象上同时需要单个属性和电子邮件地址列表。

您可能还需要考虑使Emails属性设置器protected ,以防止外部代码更改对象的数据。

如果必须实现此接口,并且希望EmailAddress属性始终引用集合中的第一封电子邮件,则可以尝试此代码。

public class Contact : IPerson, ILocation
{
  public Contact()
  {
    // Initialize the emails list
    this.Emails = new List<Emails>();
  }

  [MaxLength(256)]
  public string EmailAddress
  { 
    get
    {
      // You'll need to decide what to return if the first email has not been set.
      // Replace string.Empty with the appropriate value.
      return this.Emails.Count == 0 ? string.Empty : this.Emails[0].ToString();
    } 
    set
    {
      if (this.Emails.Count == 0)
      {
        this.Emails.Add(new Emails());
      }
      this.Emails[0].EmailAddress = value;
    }
  }

  public virtual IList<Emails> Emails { get; set; }
}

编辑:我一开始并不理解这个问题。

在这种情况下,我不确定你想要做什么是有道理的。 您正在从getter上收集的电子邮件中收集第一封电子邮件; 那么你想要什么样的行为者? 它可以(a)将设置值更新或插入集合中的第一个位置,或者(b)只需在设置时将电子邮件添加到集合中。 我不确定我是否会允许设置它,只需要得到并留下它。

我还会重命名属性FirstEmail或其他东西,所以很明显它来自可能的电子邮件集合。

  public string FirstEmailAddress { 
      get{
         return this.Emails.Count > 0 ? this.Emails.First().ToString() : string.Empty;
      } 
  }

通常,当您想要向世界“展示”内部集合时,您所做的就是将其作为属性并仅创建一个getter。 这样您就无法设置整个集合,如Contact.Emails = new ICollection<Email>() ,这是一种不好的做法。 但您可以通过Contacts.Emails访问该集合并迭代它或添加项目等。

如果您愿意,还可以向此属性添加索引器: http//msdn.microsoft.com/en-us/library/vstudio/6x16t2tx(v = vs.100).aspx

从你的评论,

我在联系人和他们的电子邮件之间有一对多(因此集合)。 因为我继承了一个接口,所以我不能排除EmailAddress属性(来自界面)。 所以我不确定从哪里拿这个。 我可以忽略这个集合并通过这种关系来做吗?

你不应该允许public二传手。 在标记虚拟时使其protected

public virtual ICollection<Emails> Emails { get; protected set; }

对于您的EmailAddress setter,您可以使用以下内容

[MaxLength(256)]
public string EmailAddress 
{ 
    get
    {
        return this.Emails.DefaultIfEmpty(new EMail()).First().EmailAddress;
    } 
    set
    {
        if (Emails == null)
        {
            Emails = new Collection<Email>(); 
        }
        Emails.Items.Insert(0, new EMail {EmailAddress = value}); 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM