【问题标题】:C# how to inherit from default constructorC#如何从默认构造函数继承
【发布时间】:2013-10-24 11:38:50
【问题描述】:

我有一个带有 2 个构造函数的简单类。

第一个(默认)不带参数的构造函数构造所有属性,因此一旦实例化该对象,它们就不为空。

第二个采用 int 参数的构造函数做了更多的逻辑,但它也需要完全按照默认构造函数在设置属性方面所做的事情。

我可以从这个默认构造函数继承,所以我不重复代码吗?

下面的代码...

public class AuctionVehicle
{
    public tbl_Auction DB_Auction { get; set; }
    public tbl_Vehicle DB_Vehicle { get; set; }
    public List<String> ImageURLs { get; set; }
    public List<tbl_Bid> Bids { get; set; }
    public int CurrentPrice { get; set; }

    #region Constructors

    public AuctionVehicle()
    {
        DB_Auction = new tbl_Auction();
        DB_Vehicle = new tbl_Vehicle();
        ImageURLs = new List<string>();
        ImageURLs = new List<string>();
    }

    public AuctionVehicle(int AuctionID)
    {
        // call the first constructors logic without duplication...

        // more logic below...
    }
}

【问题讨论】:

  • 将代码移动到另一个函数,比如 init 并从两个构造函数中调用它。但是,嘿,这里的继承不是正确的词。
  • 这不是继承,它被称为构造函数链或构造函数伸缩。
  • @Jack 有效,除非您设置的字段是 readonly,否则它们不能从 Init() 设置

标签: c# oop constructor default-constructor


【解决方案1】:
public AuctionVehicle(int AuctionID) : this()
    {
        // call the first constructors logic without duplication...
        // more logic below...
    }

或将其分解为包含通用逻辑的私有方法。

【讨论】:

    【解决方案2】:

    你可以这样做:

    public AuctionVehicle(int AuctionID) : this() 
    {
       ...
    }
    

    【讨论】:

      【解决方案3】:
      public AuctionVehicle(int AuctionID)
          : this()// call the first constructors logic without duplication...
      {
          // more logic below...
      }
      

      【讨论】:

        【解决方案4】:

        c#中不允许从构造函数继承

        原因:-

        如果允许构造函数继承,那么基类构造函数中必要的初始化可能很容易被省略。这可能会导致难以追踪的严重问题。例如,如果一个新版本的基类出现一个新的构造函数,你的类会自动获得一个新的构造函数。这可能是灾难性的。

        【讨论】:

        • 1) 这不是继承,OP 只有一个类。他们只是使用了错误的术语。 2)您可以调用您选择的基本构造函数,例如MyConstructor : base() {}。虽然你是对的,这些不是自动继承的。基本构造函数的效果与protected 方法相同,但仅对直接后代可用。
        猜你喜欢
        • 2015-07-09
        • 1970-01-01
        • 2016-03-24
        • 2017-10-04
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        相关资源
        最近更新 更多