加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中设置ICollection属性的值

发布时间:2020-12-15 21:45:03 所属栏目:百科 来源:网络整理
导读:我的类继承了一个接口,所以我需要在Person类中拥有emailaddress属性. 我的问题是获得房产和设置房产的最佳方式是什么 public class Contact : IPerson,ILocation{ ... [MaxLength(256)] public string EmailAddress { get{ return this.Emails.First().ToStr
我的类继承了一个接口,所以我需要在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; }

解决方法

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

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

如果必须实现此接口,并且希望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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读