<分区>
Possible Duplicate:
C# - Is there a better alternative than this to ‘switch on type’?
考虑经典:
class Widget { }
class RedWidget : Widget { }
class BlueWidget : Widget { }
在大多数情况下,在我的 UI 中,我可以同样对待所有 Widget
。但是,存在细微差异,我需要通过 if
或 switch
来解决。
可能的方法:
枚举指标 - 由构造函数设置
enum WidgetVariety { Red, Blue }
class Widget {
public WidgetVariety Variety { get; protected set; }
}
class RedWidget : Widget {
public RedWidget() {
Variety = Red;
}
}
// Likewise for BlueWidget...
switch (mywidget.Variety) {
case WidgetVariety.Red:
// Red specific GUI stuff
case WidgetVariety.Blue:
// Blue specific GUI stuff
}
使用是
Widget w = ...;
if (w is RedWidget) {
(RedWidget)w ...
}
else if (w is BlueWidget) {
(BlueWidget)w ...
}
我采用这种方法的原因是 1) 大多数代码已经以这种方式编写,但更加丑陋。 2) 90% 的代码是相同的 - 基本上只是 GridView 中的一列需要根据类型进行不同的处理。
您会推荐哪个? (或者谁有更好的解决方案?)
编辑 我知道我可能会被推荐给访问者模式,但在这种情况下,对于稀疏、细微的差异来说,这似乎很复杂。
编辑 2
因此,我很难整理出一个特别的区别,即这列在两种类型之间是不同的。在一种情况下,它检索一个 bool
值,并将其分配给网格单元格。在另一种情况下,它获得一个字符串值。
我想在这种情况下,很明显我可以定义:
public object virtual GetColumn4Data();
public override GetColumn4Data() { return m_boolval; }
public override GetColumn4Data() { return m_mystring; }
由于使用了 object
,最初我觉得这是错误的。但是, 是我在单元格中分配给的属性类型,所以当然这是有道理的!
今天在办公室似乎太久了......