首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得非给定枚举值的枚举值

如何获得非给定枚举值的枚举值
EN

Stack Overflow用户
提问于 2017-06-01 07:17:15
回答 4查看 74关注 0票数 1

我想得到在一个给定的枚举中存在的任何值,而不是n。如果我有一个枚举,我将尝试更好地解释它。

代码语言:javascript
复制
public enum EFileFormat
{
    Rtf,
    Word,
    Pdf,
    Html,
    Txt
}

和带有枚举的任意值的变量,例如

代码语言:javascript
复制
EFileFormat.Word

我想得到枚举的任何值,它不是"EFileFormat.Word“。我已经讨论了这段代码,但我认为必须有一种更优雅的方法:

代码语言:javascript
复制
var name = Enum.GetName(typeof(EFileFormat), format);
var names = Enum.GetNames(typeof(EFileFormat)).Where(n => !n.Equals(name));
var otherFormat = (EFileFormat)Enum.Parse(typeof(EFileFormat), names.First());

有什么想法吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-06-01 08:06:14

将标志值分配给Enum将允许您这样做-如果您可以更改Enum值。

请参阅:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/enumeration-types#enumeration-types-as-bit-flags

代码语言:javascript
复制
[Flags]
public enum EFileFormat
{
    Rtf = 0x1,
    Word = 0x2,
    Pdf = 0x4,
    Html = 0x8,
    Txt = 0x16
}

...

// this will be equal to only word
var word = EFileFormat.Word;

// this will be equal to every value except word    
var notWord = ~EFileFormat.Word;

// this will be equal to Html and Pdf
var value = EFileFormat.Html | EFileFormat.Pdf;

// this will be equal to Html
var html = value - EFileFormat.Pdf;

// this will check if a value has word in it
if(notWord == (notWord & EFileFormat.Word))
{
   // it will never reach here because notWord does not contain word,
   // it contains everything but word.
}
票数 1
EN

Stack Overflow用户

发布于 2017-06-01 07:29:33

enumValue <-> enumName使用GetValues方法代替多重转换。

Linq First()方法有一个带有谓词的重载,使用它可以避免Where()

代码语言:javascript
复制
var format = EFileFormat.Word;      
var result = Enum.GetValues(typeof(EFileFormat))
    .OfType<EFileFormat>()
    .First(x => x != format);
票数 1
EN

Stack Overflow用户

发布于 2017-06-01 07:25:26

您可以从值而不是像这样的名称进行处理;

代码语言:javascript
复制
var someOtherFormat =(EFileFormat)Enum.GetValues(typeof(EFileFormat).First(i=>i =! (int)EFileFormat.Word);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44300955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档