C#继承:当我调用派生类构造函数时,如何调用基类构造函数

时间:2010-12-14 22:02:21

标签: c# inheritance constructor

我试图弄清楚在调用派生类构造函数时如何调用基类构造函数。

我有一个名为“AdditionalAttachment”的类,它继承自System.Net.Mail.Attachment。我已经为我的新类添加了2个属性,以便我可以拥有现有Attachment类的所有属性和我的新属性< / p>

public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}

早些时候,我曾经创建像

这样的构造函数

// objMs是一个MemoryStream对象

Attachment objAttachment = new Attachment(objMs, "somename.pdf")

我想知道如何为我的类创建相同类型的构造函数,它将执行与基类的上述构造函数相同的操作

4 个答案:

答案 0 :(得分:13)

这会将您的参数传递给基类的构造函数:

public AdditionalAttachment(MemoryStream objMs, string displayName) : base(objMs, displayName)
{
   // and you can do anything you want additionally 
   // here (the base class's constructor will have 
   // already done its work by the time you get here)
}

答案 1 :(得分:7)

您可以编写一个调用类基构造函数的构造函数:

public AdditionalAttachment(MemoryStream objMs, string filename)
    : base(objMs, filename)
{
}

答案 2 :(得分:7)

使用此功能:

public AdditionalAttachment(MemoryStream ms, string name, etc...)
       : base(ms, name) 
{
}

答案 3 :(得分:3)

public class AdditionalAttachment: Attachment
{
   public AdditionalAttachment(param1, param2) : base(param1, param2){}
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}