使用基本构造函数时,C#避免重复

时间:2016-08-31 11:31:31

标签: c# .net architecture c#-5.0

有两个类,NodeBase和ContentSectionNode,它们继承自抽象类NodeBase,我想知道是否有任何方法可以避免在ContentSectionNode构造函数中重复一段代码,同时也委托给基类构造

抽象NodeBase类ctors看起来像这样:

protected NodeBase(string tagType, string content)
  : this()
{
  TagType = tagType;
  Content = content;
}

protected NodeBase(Guid? parentId, int? internalParentId, string tagType, string content) 
  : this(tagType, content)
{
  ParentId = parentId;
  InternalParentId = internalParentId;
}

ContentSectionNode类看起来像这样:

public ContentSectionNode(Guid createdBy)
  : this()
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

public ContentSectionNode(Guid createdBy, string tagType, string content)
  :base(tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

public ContentSectionNode(Guid createdBy, Guid? parentId, int? internalParentId, string tagType, string content)
  : base(parentId, internalParentId, tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}

我想知道是否有任何方法可以避免重复

_createdBy = createdBy;
_createdAt = DateTime.Now;
UpdatedAt = _createdAt;
UpdatedBy = _createdBy;

阻止ContentSectionNode类的所有ctors。 请注意,_createdBy,_createdAt和UpdatedBy,UpdatedAt字段/道具只能从ContentSectionNode类访问,并且只能在那里设置。

该项目使用的是C#5.0,因此没有自动属性初始值设定项。 谢谢!

1 个答案:

答案 0 :(得分:7)

喜欢这个吗?

public ContentSectionNode(Guid createdBy)
  : this(createdBy,null,null, null, null)
{
}

public ContentSectionNode(Guid createdBy, string tagType, string content)
  : this(createdBy, null, null tagType, contect)
{
}

public ContentSectionNode(Guid createdBy, Guid? parentId, int? internalParentId, string tagType, string content)
  : base(parentId, internalParentId, tagType, content)
{
  _createdBy = createdBy;
  _createdAt = DateTime.Now;
  UpdatedAt = _createdAt;
  UpdatedBy = _createdBy;
}