在 C# 中设置 ICollection 属性的值

utd*_*878 5 c# properties icollection

我的类继承了一个接口,因此我需要在 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; }
}
Run Code Online (Sandbox Code Playgroud)

本质上,我试图让班级允许不止一封电子邮件。

为了充分披露,我对此很陌生,我可能没有问正确的问题,但我已经搜索了一天半,但没有看到这样的东西(并不是说我认为这是不寻常的)并且可以使用的洞察力。

电子邮件类属性:

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

[MaxLength(256)]
    public string EmailAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)

Jer*_*ine 1

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

您可能还需要考虑创建Emails属性 setter 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; }
}
Run Code Online (Sandbox Code Playgroud)