我有以下代码,并且想知道是否有一种方法可以在最后一节(仅复制文件)中写入按位运算符,以包括将其设置为All值,然后在一行中删除其他两个值。
private void cbInstallType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbInstallType.Text == "Full Install")
{
eventFlags = GBFEvents.All;
}
else if (cbInstallType.Text == "DB Only")
{
eventFlags = (GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
}
else if (cbInstallType.Text == "Copy Files Only")
{
eventFlags = GBFEvents.All;
eventFlags &= ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
}
}
GBFEvents的定义如下:
public enum GBFEvents
{
NONE = 0,
InitGBFSQL = 1 << 0,
ServiceIISControlDown = 1 << 1,
SetWebConfigValues = 1 << 2,
ReadFilelists = 1 << 3,
CopyFiles = 1 << 4,
FixWebConfigValues = 1 << 5,
BuildAppPaths = 1 << 6,
PerformDatabaseUpdate = 1 << 7,
ServiceIISControlUp = 1 << 8,
All = ~(-1 << 9)
}
答案 0 :(得分:3)
将其更改为一行只是扩展事情的非常简单的情况。因此,请逐步进行操作:
var eventFlags = GBFEvents.All;
eventFlags &= ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
如果我们展开&=
,我们将得到:
var eventFlags = GBFEvents.All;
eventFlags = eventFlags & ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
如果然后在第二行中内联使用eventFlags,则会得到:
var eventFlags = GBFEvents.All & ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
答案 1 :(得分:3)
我知道您的问题answer已经可以接受,但是我仍然希望您的enum
中这样的内容:
public enum GBFEvents
{
NONE = 0,
InitGBFSQL = 1 << 0,
ServiceIISControlDown = 1 << 1,
SetWebConfigValues = 1 << 2,
ReadFilelists = 1 << 3,
CopyFiles = 1 << 4,
FixWebConfigValues = 1 << 5,
BuildAppPaths = 1 << 6,
PerformDatabaseUpdate = 1 << 7,
ServiceIISControlUp = 1 << 8,
/* Helpers */
AllDBEvents = InitGBFSQL | PerformDatabaseUpdate,
AllServiceEvents = ServiceIISControlDown | ServiceIISControlUp,
AllConfigEvents = SetWebConfigValues | FixWebConfigValues,
AllFileEvents = ReadFilelists | CopyFiles | BuildAppPaths,
All = AllDBEvents | AllServiceEvents | AllConfigEvents | AllFileEvents
}
(例如,我可能误称了BuildAppPaths
,您可能认为它与Config
的关联性更高)
然后您的代码将是:
eventFlags = AllServiceEvents | AllConfigEvents | AllFileEvents;
(其他路径仅使用AllDbEvents
)
对我来说,这使我更清楚地阅读到“仅复制文件”不仅是在复制文件,而且不必在该行上同时拥有大量的选项|
。并且enum
中的这些帮助程序值也可以在其他领域重用。
主要思想是使事件的“命名组”在枚举中明确显示,而不是必须将其正确组合到代码的其他部分。