Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#如何从默认构造函数继承_C#_Oop_Constructor_Default Constructor - Fatal编程技术网

C#如何从默认构造函数继承

C#如何从默认构造函数继承,c#,oop,constructor,default-constructor,C#,Oop,Constructor,Default Constructor,我有一个包含2个构造函数的简单类 第一个不带参数的(默认)构造函数构造所有属性,因此一旦实例化该对象,它们就不会为null 接受int参数的第二个构造函数执行更多的逻辑,但它也需要执行默认构造函数在设置属性方面所执行的操作 我可以从这个默认构造函数继承什么,这样我就不会复制代码了吗 下面的代码 public class AuctionVehicle { public tbl_Auction DB_Auction { get; set; } public tbl_Vehicle D

我有一个包含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...
    }
}
公共级拍卖车辆
{
公开tbl_拍卖DB_拍卖{get;set;}
公共tbl_车辆DB_车辆{get;set;}
公共列表ImageURLs{get;set;}
公共列表出价{get;set;}
public int CurrentPrice{get;set;}
#区域构造函数
公开拍卖车辆()
{
DB_拍卖=新的tbl_拍卖();
DB_车辆=新的tbl_车辆();
ImageURLs=新列表();
ImageURLs=新列表();
}
公共拍卖车辆(国际拍卖ID)
{
//不重复地调用第一个构造函数逻辑。。。
//下面是更多的逻辑。。。
}
}

或者将其分解为包含公共逻辑的私有方法。

您可以这样做:

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

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

原因:-


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

将代码移动到另一个函数,比如init,然后从两个构造函数调用它。但是,嘿,这里的继承不是正确的词。这不是继承,它被称为构造函数链接或构造函数伸缩。除非您设置的字段是
readonly
,否则@Jack可能会重复,否则无法从
Init()
1)设置这些字段。这不是继承,实际上,OP只有一个类。他们只是用错了词。2) 您可以调用自己选择的基本构造函数,例如
MyConstructor:base(){}
。虽然你是对的,这些不是自动继承的。基本构造函数与受保护的方法无效,但仅对直接后代可用。
public AuctionVehicle(int AuctionID) : this() 
{
   ...
}
public AuctionVehicle(int AuctionID)
    : this()// call the first constructors logic without duplication...
{
    // more logic below...
}