Why do I have both of these constructors in my class?
In my project, I see that I have two constructors. The debugger only ever attaches to the second constructor - why do I h开发者_StackOverflow中文版ave both?
public EventDialog()
{
// Required for Windows Form Designer support
InitializeComponent();
m_timer.Interval = SystemInformation.DoubleClickTime;
m_timer.AutoReset = false;
m_timer.Elapsed +=new System.Timers.ElapsedEventHandler(TimerElapseCallback);
} // Constructor
public EventDialog(string[] list)
{
// Required for Windows Form Designer support
InitializeComponent();
if(list != null)
{
foreach(string s in list)
{
if(s.Trim() != string.Empty)
m_leafComboBox.Items.Add(s.Trim());
}
}
m_timer.Interval = SystemInformation.DoubleClickTime;
m_timer.AutoReset = false;
m_timer.Elapsed +=new System.Timers.ElapsedEventHandler(TimerElapseCallback);
}
//
// Required for Windows Form Designer support
//
Only the comment in the first constructor is accurate. You can't design the form without a default constructor. Make it look better like this:
public EventDialog(string[] list) : this()
{
if (list != null)
{
// etc..
}
}
Note the added this() to call the default constructor. You now only have to add the special constructor code.
The parameter-less constructor (the first one) is required because otherwise Visual Studio designer won't be able to create an instance of this class (I suppose that's a Form class) to show in in the UI designer.
The second constructor is most probably created by a developer to pass some extra parameters when creating the dialog manually from code.
BTW I'd better write it like this:
public EventDialog(string[] list) : this() { ... }
The reason that only the second constructor is attached is that there must exist a call which passes a value to the constructor and the second constructor does not call the parameterless constructor. If you define a constructor with parameters, it will be the only constructor that is accepted. I.e., a parameterless constructor will no longer exist on the class. However, if you want to continue to allow other code to instantiate the class using a parameterless constructor and you want a constructor with parameters, you must declare both.
精彩评论