我将竭尽全力在这里解释我的愿景。 这是一个非常突出的例子。 缩略语 Bag s and they all hold their own special category of Marble
. 每种类型的<代码>Marble <>/code>都有自己的一套尼克名称(string
)。
不幸的是,除了马布莱人外,还有其他东西,大通人在这里赢得帮助。
// Bags
abstract class Bag {
protected Type MarbleType { get; }
protected List<Marble> _marbles;
public void DumpBag()
{ ... }
}
class RedBag : Bag {
override Type MarbleType { get { return typeof(RedMarble); } }
}
class BlueBag : Bag {
override Type MarbleType { get { return typeof(BlueMarble); } }
}
// Marbles
abstract class Marble {
public static IEnumerable<string> Nicknames {
get {
return new List<string>() {
"Marble", "RollyThing"
}
}
}
}
class RedMarble : Marble {
public static IEnumerable<string> Nicknames {
get {
return new List<string>(Marble.Nicknames) {
"Ruby"
};
}
}
}
class BlueMarble : Marble { ... }
因此,我们现在了解细节,即
Bag b = new RedBag();
b.GetMarbles();
b.DumpBag();
我谨印刷:
Bag of Marbles (aka "Marble", "RollyThing", Ruby"):
- Marble 1
- Marble 2
...
我们认为,为了印刷这一标题,Bag
必须能够了解衍生类型的Marble
,而不论实际情况如何。 本条对<条码>的“名称条码>进行了分类,但同时也对衍生的<条码>。
DumpBag
needs to do a kind of static virtual call . I ve started implementing DumpBag
with the following:
public void DumpBag() {
PropertyInfo pi = this.MarbleType.GetProperty("Nicknames", BindingFlags.Static);
IEnumerable<string> nicknames = pi.GetValue(null, null); // No instance
StringBuilder sb = new StringBuilder("Bag of Marbles (aka ");
foreach (string nn in nicknames)
sb.Append(""" + nn + "", ");
Console.WriteLine(sb.ToString());
...
}
我的问题:
- Is this sane? Hopefully I have (or I can) explain my rationale for why I ve gone this route.
- I get a warning (of course) that
RedMarble.Nicknames
hidesMarble.Nicknames
. Does it seem valid to go ahead and mark itnew
?