Constructors With Same Arguments?
I have a WinForm that I want to be able to construct using two different ID values. So for instance:
var f1 = new Form(table1Id);
var f2 = new Form(table2Id);
The first constructor wo开发者_运维知识库uld build the form based on data in table1, the second constructor would build the form based on data in table2. The problem is, if I have two constructors that take an int, there is no differentiating between the two. What is the best way around this problem?
Consider a factory approach instead of a constructor. Named methods are a way to disambiguate when the parameter types are the same but mean different things. For example
public static Form CreateFromTable1(int id)
{
// instantiate, build form
return form;
}
public static Form CreateFromTable2(int id)
{
// instantiate, build form
return form;
}
class MyForm : Form
{
public MyForm(int id)
{
// logic to distinguish id goes here
}
}
Without seeing code it's hard to confirm this, but by your very explanation this class is violating the Single Responsibility Principle.
Assuming the forms only differ by data, have the constructor take the actual data instead IDs, which I assume are used to get the data.
If they differ substantially by the content, they should be two distinct forms (possible with a common, abstract parent class).
Based on my past experiences, having that one form to rule them all mentality is just going to create a maintenance nightmare. Spend some time studying the SOLID principles (S = Single Responsibility Principle) and you'll be pleasantly surprised with the code you start writing.
In this case I'd create an Enum and pass one of its values as an argument, indicating what kind of table is given.
I would use an Initialize method, something like:
var f1 = new Form();
f1.InitA(table1Id);
var f2 = new Form();
f2.InitB(table2Id);
精彩评论