c# – 将枚举标志附加到循环中的参数(按位追加)
发布时间:2020-12-15 20:03:09 所属栏目:百科 来源:网络整理
导读:在C#中,我试图将“值”添加到接受枚举标志的参数中.我可以在一行上使用按位运算符“|”,但我似乎无法在循环中追加参数. 我将以下Enum指定为Flags. [Flags]public enum ProtectionOptions{ NoPrevention = 0,PreventEverything = 1,PreventCopying = 2,Preven
在C#中,我试图将“值”添加到接受枚举标志的参数中.我可以在一行上使用按位运算符“|”,但我似乎无法在循环中追加参数.
我将以下Enum指定为Flags. [Flags] public enum ProtectionOptions { NoPrevention = 0,PreventEverything = 1,PreventCopying = 2,PreventPrinting = 4,PrintOnlyLowResolution = 8 } 现在,我可以轻松地使用以下代码向参数添加标志值: myObj.Protection = ProtectionOptions.PreventEverything | ProtectionOptions.PrintOnlyLowResolution; 但是,我想要做的是从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()); } 从概念上讲,这就是我想要的,但我不能“=”循环中的值到参数. 解决方法
你不需要拆分.如果使用枚举定义中的[Flags]属性,Enum.Parse能够解析多个值.只需解析并使用| =运算符“添加”标志.
string protectionOptionsString = "NoPrevention,PreventPrinting"; myObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions),protectionOptionsString); 有关枚举,位标志和System.Enums方法的更多信息,请参阅我的教程:http://motti.me/s1D 以下是整个教程的链接:http://motti.me/s0 我希望这有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |