找到将属性应用于代码的最佳方法
本文关键字:最佳 方法 代码 应用于 属性 | 更新日期: 2023-09-27 18:11:48
很抱歉让人混淆了标题。我使用第三方控件的蔓延,它有一个comboBoxCellType()。在我的代码中大约有20个地方我有这样的代码:
ComboBoxCellType cbo = new ComboBoxCellType()
cbo.OtherStuff...
现在我想让所有这样的代码都有一个额外的属性listwidth =0;所以比如:
ComboBoxCellType cbo = new ComboBoxCellType()
cbo.listwidth=0;
cbo.OtherStuff
一种方法是搜索代码并手动添加。但我想知道是否有更好的方法使用继承和重写来做到这一点?
您可以创建一个静态类,用于新建ComboBoxCellType。
像这样:
public static class ComboBoxCellTypeFactory
{
public static ComboBoxCellType Create()
{
return new ComboBoxCellType(){listwidth = 0};
}
}
这样你就可以新建ComboBoxCellType实例,listwidth属性设置为0,如下所示:
ComboBoxCellType cbo = ComboBoxCellTypeFactory.Create();
cbo.OtherStuff...
将ComboBoxCellType
的创建和初始化封装到一个方法中,并在之前执行此操作的每个位置调用该方法。
一般来说,如果您发现自己在重复代码,请查看是否可以将代码提取到可以调用的方法中。保持代码DRY。
类似:
private ComboBoxCellType BuildComboBoxCellType()
{
ComboBoxCellType cbo = new ComboBoxCellType()
cbo.listwidth=0;
cbo.OtherStuff...
return cbo;
}
在原始代码中:
ComboBoxCellType cbo = BuildComboBoxCellType();
如果您可以访问源代码,我建议放置一个this。在ComboBoxCellType的构造函数中,listwidth = 0