将枚举值数组转换为位标志组合
如何在 C# 2.0 中以最简单、最优的方式从枚举值数组创建位标志组合。我实际上已经找到了解决方案,但我只是对这里的复杂性不满意。
enum MyEnum
{
Apple = 0,
Apricot = 1,
Breadfruit = 2,
Banana = 4
}
private int ConvertToBitFlags(MyEnum[] flags)
{
string strFlags = string.Empty;
foreach (MyEnum f in flags)
{
strFlags += strFlags == string.Empty ?
Enum.GetName(typeof(MyEnum), f) :
"," + Enum.GetName(typeof(MyEnum), f);
}
return (int)Enum.Parse(typeof(MyEnum), strFlags);
}
How to create a bit-flag combination from an array of enum values in the simplest most optimal way in C# 2.0. I have actually figured out a solution but I am just not satisfied with the complexity here.
enum MyEnum
{
Apple = 0,
Apricot = 1,
Breadfruit = 2,
Banana = 4
}
private int ConvertToBitFlags(MyEnum[] flags)
{
string strFlags = string.Empty;
foreach (MyEnum f in flags)
{
strFlags += strFlags == string.Empty ?
Enum.GetName(typeof(MyEnum), f) :
"," + Enum.GetName(typeof(MyEnum), f);
}
return (int)Enum.Parse(typeof(MyEnum), strFlags);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
OTOH,您应该使用
FlagsAttribute
来提高类型安全性:更好的是,通过使用
FlagsAttribute
您可以避免使用MyEnum[]
完全,从而使该方法变得多余。OTOH, you should use the
FlagsAttribute
for improved type safety:Better still, by using
FlagsAttribute
you may be able to avoid using aMyEnum[]
entirely, thus making this method redundant.这是一个较短的通用扩展版本:
并使用:
Here's a shorter generic extension version:
And using: