我什么时候需要在C#中调用base()?

时间:2014-06-11 15:13:26

标签: c# inheritance constructor

我的BaseClass构造函数被调用,而我在派生类中有一个构造函数,所以什么时候需要调用base()?

class BaseClass
{
    public BaseClass()
    {
        Debug.Print("BaseClass");
    }
}

class InheritedClass : BaseClass
{
    public InheritedClass()
    {
        Debug.Print("InheritedClass");
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    InheritedClass inheritedClass = new InheritedClass();
}

输出

'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll'
'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
BaseClass
InheritedClass
The thread 'vshost.RunParkingWindow' (0x12b4) has exited with code 0 (0x0).
The thread '<No Name>' (0x85c) has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

2 个答案:

答案 0 :(得分:9)

当你有一个非默认的基本构造函数时(例如,使用param重载)。

示例:

public class BaseClass
{
  public BaseClass(int number)
  {
     // DoSomething
  }

  public BaseClass(string str)
  {
    // Do Something
  }
}

public class DerivedClass : BaseClass
{
   public DerivedClass(): base(7){} 
   public DerivedClass(string str) : base(str){}
}

答案 1 :(得分:0)

自动调用默认的base()构造函数。

public class DerivedClass : BaseClass
{
   public DerivedClass(): base() // No harm done, but this is redundant
   {}
   //same as
   public DerivedClass()
   {}
}

唯一没有自动调用的是其他东西,比如参数化的基础构造函数。正如Amir Popovich的出色答案一样。