2011-10-18 28 views
0

对于易混淆的标题感到抱歉。 我对Spreads使用第三方控件,它有一个comboBoxCellType()。 在我的代码有喜欢的20个地方,我有这样的代码:找到将财产应用于代码的最佳方式

ComboBoxCellType cbo = new ComboBoxCellType() 
cbo.OtherStuff... 

现在我想这样的代码的所有出现次数有所谓的额外的属性listwidth = 0;所以 类似:

ComboBoxCellType cbo = new ComboBoxCellType() 
cbo.listwidth=0; 
cbo.OtherStuff 

一个办法就是搜索代码和手动添加。但我想知道是否有更好的方法使用继承和重写来做到这一点?

回答

1

您可以创建一个静态类,用于新建ComboBoxCellType。

事情是这样的:

public static class ComboBoxCellTypeFactory 
{ 
    public static ComboBoxCellType Create() 
    { 
     return new ComboBoxCellType(){listwidth = 0}; 
    } 
} 

有了这个,你可以用listwidth属性设置为0喜欢这个新达ComboBoxCellType实例:

ComboBoxCellType cbo = ComboBoxCellTypeFactory.Create(); 
cbo.OtherStuff... 
+0

然后,您可以使用ComboBoxCellType cbo = ComboBoxCellTypeFactory.Create()来搜索/替换'ComboBoxCellType cbo = new ComboBoxCellType();'的实例。 –

+0

谢谢,我现在就试试吧...... – Bohn

+0

嗯..这个编译错误是什么? “静态类'MyApplication.ComboBoxCellTypeFactor'不能从类型'FarPoint.Win.Spread.CellType.ComboBoxCellType'派生,静态类必须从对象派生。” – Bohn

1

将一个ComboBoxCellType的创建和初始化封装到一个方法中,并从以前执行此操作的每个位置调用该方法。

一般来说,如果您发现自己重复了代码,请参阅是否可以将代码提取到可以调用的方法中。保持您的代码DRY

喜欢的东西:

private ComboBoxCellType BuildComboBoxCellType() 
{ 
    ComboBoxCellType cbo = new ComboBoxCellType() 
    cbo.listwidth=0; 
    cbo.OtherStuff... 

    return cbo; 
} 

而在你的原始代码:

ComboBoxCellType cbo = BuildComboBoxCellType(); 
+0

嗯,听起来不错。你能给我看一些代码示例,我可以明白吗?谢谢 – Bohn

+0

ohok,谢谢...以及cbo.OtherStuff在代码的不同位置上有很大不同。这不是我能做到的。所以唯一常见的事情是cbo.listwidth = 0; ...在这种情况下,我仍然触摸代码的所有位置来应用这个新的BuildComboBoxCellType()...这又像是在需要的地方编写cbo.listwidth = 0。继承在这种情况下不起作用? – Bohn

+0

@BDotA - 根据“OtherStuff”是什么,您可以使用'Func '或'Action '委托人将其分解出来。 – Oded

0

如果你有机会获得源代码,我建议把一个this.listwidth = 0的构造你的ComboBoxCellType。

+0

我不知道。这是一个商业控制。 (Farpoint Spread。) – Bohn