我最常用的迷你图案是:
VideoLookup = new ArrayList { new ArrayList { buttonVideo1, "Video01.flv" },
new ArrayList { buttonVideo2, "Video02.flv" },
new ArrayList { buttonVideo3, "Video03.flv" },
new ArrayList { buttonVideo4, "Video04.flv" },
new ArrayList { buttonVideo4, "Video04.flv" }
};
这意味着我可以将单击的按钮与 ArrayList 中的每个项目进行比较,而不是使用每个按钮都有 case 的 switch 语句。然后,当我找到匹配项时,我会启动正确的文件(尽管“查找”第二部分的操作可以是委托(delegate)或其他任何操作)。
主要的好处是我没有记住为每个 switch 语句用例添加所有正确代码的问题,我只是向查找 ArrayList 添加一个新项。
(是的,我知道使用 ArrayList 不是最好的方法,但它是旧代码。而且我知道每次循环遍历数组不如使用 switch 语句有效,但是这代码不在紧密循环中)
有没有其他人有他们使用的任何微型模式来节省时间/精力或使代码更具可读性? 它们不必只是与 GUI 相关。
更新:不要复制这段代码,我知道它很糟糕,但我没有意识到有多糟糕。请改用类似这样的东西。
Hashtable PlayerLookup = new Hashtable();
PlayerLookup.Add(buttonVideo1, "Video01.flv");
PlayerLookup.Add(buttonVideo2, "Video02.flv");
PlayerLookup.Add(buttonVideo3, "Video03.flv");
PlayerLookup.Add(buttonVideo4, "Video04.flv");
string fileName = PlayerLookup[currentButton].ToString();
最佳答案
请使用此版本。
VideoLookup = new Dictionary<Button, string> {
{ buttonVideo1, "Video01.flv" },
{ buttonVideo2, "Video02.flv" },
{ buttonVideo3, "Video03.flv" },
{ buttonVideo4, "Video04.flv" },
{ buttonVideo4, "Video04.flv" }
};
关于c# - 有用的迷你模式(不是设计模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/547539/