问题描述
可能重复:
C# - 有没有更好的替代开启类型"?
考虑经典:
class Widget { }
class RedWidget : Widget { }
class BlueWidget : Widget { }
在大多数情况下,在我的 UI 中,我可以将所有 Widget
视为相同.但是,有一些细微的差异,我需要通过 if
或 switch
.
For the most part, in my UI, I can treat all Widget
s the same. However, there are minor differences, which I need to if
or switch
through.
可能的方法:
枚举指标 - 由构造函数设置
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 中的一列需要根据类型进行不同的处理.
The reason I've resorted to this is 1) Most of the code is already somewhat written this way, but much uglier. 2) 90% of the code is identical - basically just one column in a GridView needs to be handled differently depending on the type.
你会推荐哪个?(或者任何人有更好的解决方案?)
Which would you recommend? (Or anyone have a better solution?)
编辑我知道我可能会被推荐到访问者模式,但在这种情况下,对于稀疏的、微小的差异来说,这似乎很复杂.
Edit I know I'll probably be recommended to the Visitor Pattern, but that simply seems to complicated for sparse, minor differences in this case.
编辑 2因此,我很难理清的一个特别区别是这两种类型之间的不同.在一种情况下,它检索 bool
值,并将其分配给网格单元格.在另一种情况下,它获取一个字符串值.
Edit 2
So one particular difference I was having a hard time sorting out is this column that is different between the two types. In one case, it retrieves a bool
value, and assigns that to the grid cell. In the other case, it gets a string value.
我想在这种情况下,很明显我可以定义:
I suppose in this case, it should be obvious that I could define:
public object virtual GetColumn4Data();
public override GetColumn4Data() { return m_boolval; }
public override GetColumn4Data() { return m_mystring; }
由于使用了object
,我一开始觉得这是不对的.但是,是我在单元格中分配的属性的类型,所以当然这是有道理的!
This felt wrong to me initially, due to the use of object
. However, that is the type of the property that I am assigning to in the cell, so of course this makes sense!
今天似乎在办公室太久了……
Too long at the office today it seems...
推荐答案
还有另一种可能.使用虚拟调度:
There's another possibility. Use virtual dispatch:
class Widget
{
public virtual void GuiStuff() { }
}
class RedWidget : Widget
{
public override void GuiStuff()
{
//... red-specific GUI stuff
base.GuiStuff();
}
}
class BlueWidget : Widget
{
public override void GuiStuff()
{
//... blue-specific GUI stuff
base.GuiStuff();
}
}
这篇关于根据类型切换行为的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!