【问题标题】:C# avoid repetition when working with base constructorsC# 使用基本构造函数时避免重复
【发布时间】:2016-08-31 19:36:10
【问题描述】:

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

抽象的 NodeBase 类 ctor 如下所示:

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 类 ctor 如下所示:

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 字段/props 只能从 ContentSectionNode 类访问,并且只能在那里设置。

该项目使用 C# 5.0,因此没有自动属性初始化程序。 谢谢!

【问题讨论】:

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


    【解决方案1】:

    像这样?

    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;
    }
    

    【讨论】:

    • 这似乎工作得很好:) 谢谢!解决方案非常简单,我只是看不到它。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多