big*_*mac 3 c# bit-manipulation enum-flags
在C#中,我试图将"值"添加到接受枚举标志的参数中.我可以在一行上使用按位运算符"|",但我似乎无法在循环中追加参数.
我将以下Enum指定为Flags.
[Flags]
public enum ProtectionOptions
{
NoPrevention = 0,
PreventEverything = 1,
PreventCopying = 2,
PreventPrinting = 4,
PrintOnlyLowResolution = 8
}
Run Code Online (Sandbox Code Playgroud)
现在,我可以轻松地使用以下代码向参数添加标志值:
myObj.Protection = ProtectionOptions.PreventEverything | ProtectionOptions.PrintOnlyLowResolution;
Run Code Online (Sandbox Code Playgroud)
但是,我想要做的,就是通过它们获得的从CSV字符串(从web.config)保护选项,循环列表,并将它们添加到我的myObj.ProtectionOptions财产.我不知道如何在循环中执行此操作而不使用按位OR"|" 运营商.这是我想要做的:
string protectionOptionsString = "NoPrevention, PreventPrinting";
string[] protectionOptions = protectionOptionsString.Split(',');
foreach (string protectionOption in protectionOptions)
{
myObj.Protection += (ProtectionOptions) Enum.Parse(typeof (ProtectionOptions), protectionOption.Trim());
}
Run Code Online (Sandbox Code Playgroud)
从概念上讲,这就是我想要的,但我不能"+ ="循环中的值到参数.
Mot*_*ked 18
你不需要拆分.如果使用枚举定义中的[Flags]属性,Enum.Parse能够解析多个值.只需解析并使用| =运算符"添加"标志.
string protectionOptionsString = "NoPrevention, PreventPrinting";
myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);
Run Code Online (Sandbox Code Playgroud)
有关枚举,位标志和System.Enums方法的更多信息,请参阅我的教程:http://motti.me/s1D
以下是整个教程的链接:http://motti.me/s0
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
10883 次 |
| 最近记录: |