2010-12-14 245 views
6

我想弄清楚當我調用派生類構造函數時如何調用基類構造函數。C#繼承:當我調用派生類構造函數時如何調用基類構造函數

我有一個名爲「AdditionalAttachment」的類,它繼承自System.Net.Mail.Attachment.I爲我的新類增加了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") 

我想知道我怎麼可以創造同一種構造上我的課,這將做同樣的事情作爲基類的上述構造的

+0

重複約2周:http://stackoverflow.com/q/4296888/492 – 2013-11-08 09:20:44

回答

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) 
} 
3
public class AdditionalAttachment: Attachment 
{ 
    public AdditionalAttachment(param1, param2) : base(param1, param2){} 
    [DataMember] 
    public string AttachmentURL 
    { 
     set; 
     get; 
    } 
    [DataMember] 
    public string DisplayName 
    { 
     set; 
     get; 
    } 
} 
+0

沒有,它只是爲了演示的目的。 – 2010-12-14 22:05:52

7

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

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

使用此功能:

public AdditionalAttachment(MemoryStream ms, string name, etc...) 
     : base(ms, name) 
{ 
} 
相關問題