【问题标题】:C# Inheritance: How to invoke the base class constructor when i call the derived class constructorC#继承:当我调用派生类构造函数时如何调用基类构造函数
【发布时间】:2010-12-14 22:02:21
【问题描述】:

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

我有一个名为“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")

我想知道如何为我的类创建与上述基类的构造函数相同的构造函数

【问题讨论】:

标签: c# inheritance constructor


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      使用此功能:

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

      【讨论】:

        【解决方案4】:
        public class AdditionalAttachment: Attachment
        {
           public AdditionalAttachment(param1, param2) : base(param1, param2){}
           [DataMember]
           public string AttachmentURL
           {
               set;
               get;
           }
           [DataMember]
           public string DisplayName
           {
               set;
               get;
           }
        }
        

        【讨论】:

        • 不是,只是为了演示。
        猜你喜欢
        • 2016-07-19
        • 2015-08-18
        • 2018-07-21
        • 2018-07-16
        • 2018-03-31
        • 2020-11-28
        • 2021-04-20
        • 1970-01-01
        • 2013-01-28
        相关资源
        最近更新 更多