c# - EnumFlags 到枚举值字符串列表 C#
问题描述
我正在尝试获取标志枚举值的字符串列表
我有两个枚举
enum example {
name0 = 0,
name1 = 1,
name2 = 2,
name3 = 3
}
//And a flagged enum
[Flags]
enum example2 {
none = 0,
name1 = 1 <<example.name1,
name2 = 1 << example.name2,
name3 = 1 << example.name3
}
我设置了一个标记的枚举。
example2 = name1 | name2;
我想做的是,从那个例子2 = name1 | 2;获取具有第一个枚举的整数值的字符串列表。
到目前为止,我已经尝试制作标记枚举的字符串列表:示例:
example2.toString()
//result: "name1, name2"
//I'm not quite sure how to proceed with this, I've read the documentation but can't find something helpful, probably to split and trim the string to get a list of names, then iterate over that list and somehow get the numeric value using the names
/*
result I'm trying to achieve:
["1", "2"] <-- List of strings of int values corresponding to those names.
*/
有谁知道这样做的好方法?
~这是我的第一个问题,如果解释不好,对不起。
解决方案
好的,提供您告诉@Rufus L 的内容,有一个简单的解决方案
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(((int)Name.TEST).ToString());
Console.WriteLine(((short)Name.TEST2).ToString());
Console.WriteLine(((long)Name.TEST3).ToString());
}
}
public enum Name
{
TEST,
TEST2,
TEST3
}
的输出是 0, 1, 2 。我用不同的类型解析它,因为也许你需要一个更大的数字。
我正在编辑我的答案以防万一,因为我认为这不完全是你需要的,但它可能会派上用场,所以我留下它,我也会添加这个,如果你想将文字字符串转换为枚举值,你会需要像这样解析它
var enumVal = (Name)Enum.Parse(typeof(Name), "TEST");
然后你可以应用我之前写的
推荐阅读
- kableextra - kableExtra 无法弄清楚如何添加 spec_plot
- laravel - Laravel - 未连接到 docker 上的数据库
- git - Jenkins pipline checkout 使用副本而不是 git clone
- neo4j - 未创建或更新节点之间的关系
- pine-script - PinScript:策略关闭
- postgresql - Postgresql中的时间窗口滚动总和
- javascript - Highcharts 瀑布图在一个系列中显示未知数
- ffmpeg - 将任何输入视频文件转换为 mxf 失败
- arrays - 如何快速打印字符串数组的单个元素
- c++ - 从曲线和线条生成文本