C#继承:当我调用派生类构造函数时如何调用基类构造函数
问题描述:
我想弄清楚当我调用派生类构造函数时如何调用基类构造函数。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")
我想知道我怎么可以创造同一种构造上我的课,这将做同样的事情作为基类的上述构造的
答
这将通过你的参数为基类的构造函数:
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 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
答
您可以编写调用基类构造函数的构造函数:
public AdditionalAttachment(MemoryStream objMs, string filename)
: base(objMs, filename)
{
}
答
使用此功能:
public AdditionalAttachment(MemoryStream ms, string name, etc...)
: base(ms, name)
{
}
重复约2周:http://stackoverflow.com/q/4296888/492 – 2013-11-08 09:20:44