我想得到在一个给定的枚举中存在的任何值,而不是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());有什么想法吗?
发布于 2017-06-01 08:06:14
将标志值分配给Enum将允许您这样做-如果您可以更改Enum值。
[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.
}发布于 2017-06-01 07:29:33
enumValue <-> enumName使用GetValues方法代替多重转换。
Linq First()方法有一个带有谓词的重载,使用它可以避免Where()。
var format = EFileFormat.Word;
var result = Enum.GetValues(typeof(EFileFormat))
.OfType<EFileFormat>()
.First(x => x != format);发布于 2017-06-01 07:25:26
您可以从值而不是像这样的名称进行处理;
var someOtherFormat =(EFileFormat)Enum.GetValues(typeof(EFileFormat).First(i=>i =! (int)EFileFormat.Word);https://stackoverflow.com/questions/44300955
复制相似问题