簡體   English   中英

C#繼承:當我調用派生類構造函數時,如何調用基類構造函數

[英]C# Inheritance: How to invoke the base class constructor when i call the derived class constructor

我試圖弄清楚當我調用派生類構造函數時如何調用基類構造函數。

我有一個名為“AdditionalAttachment”的類,它繼承自System.Net.Mail.Attachment。我已經為我的新類添加了2個屬性,以便我可以使用我的新屬性獲得現有Attachment類的所有屬性

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")

我想知道如何為我的類創建相同類型的構造函數,它將執行與基類的上述構造函數相同的操作

這會將您的參數傳遞給基類的構造函數:

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

您可以編寫一個調用類基構造函數的構造函數:

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

使用此功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM