[英]How to get any enum value which is not a given enum value
我想获得给定枚举中不存在的n的任何值。 鉴于我有一个枚举,我会尽力解释一下
public enum EFileFormat
{
Rtf,
Word,
Pdf,
Html,
Txt
}
还有一个具有枚举的任意值的变量
EFileFormat.Word
我想获取不是“ EFileFormat.Word”的任何枚举值。 我已经看过这段代码,但是我认为必须存在一种更优雅的方法:
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());
有任何想法吗?
代替多枚举转换enumValue <-> enumName使用GetValues
方法。
Linq First()
方法具有谓词的重载,请使用它避免Where()
var format = EFileFormat.Word;
var result = Enum.GetValues(typeof(EFileFormat))
.OfType<EFileFormat>()
.First(x => x != format);
如果可以更改Enum值,则将标志值分配给Enum将允许您执行此操作。
请参阅: https : //docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/enumeration-types#enumeration-types-as-bit-flags
[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.
}
您可以使用值代替类似的名称;
var someOtherFormat =(EFileFormat)Enum.GetValues(typeof(EFileFormat).First(i=>i =! (int)EFileFormat.Word);
var result = Enum.GetValues(typeof(EFileFormat))
.OfType<EFileFormat>()
.Where(x => !x.Equals(EFileFormat.Word)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.