我有一个带有2个构造函数的简单类。
不带参数的第一个(默认)构造函数构造所有属性,因此在实例化此对象后它们不为null。
采用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...
}
}
答案 0 :(得分:4)
public AuctionVehicle(int AuctionID) : this()
{
// call the first constructors logic without duplication...
// more logic below...
}
或者将其分解为包含公共逻辑的私有方法。
答案 1 :(得分:4)
你可以这样做:
public AuctionVehicle(int AuctionID) : this()
{
...
}
答案 2 :(得分:2)
public AuctionVehicle(int AuctionID)
: this()// call the first constructors logic without duplication...
{
// more logic below...
}
答案 3 :(得分:0)
在c#
中不允许继承构造函数原因: -
如果允许构造函数继承,则可能很容易省略基类构造函数中的必要初始化。这可能会导致严重的问题,难以追查。例如,如果基类的新版本与新构造函数一起出现,则您的类将自动获得新的构造函数。这可能是灾难性的。