有没有一种简单的方法来一个C#枚举转换为字符串,然后再返回? [英] Is there an easy way to convert a c# enum to a string, and back again?
问题描述
我需要将列表枚举值转换为单个字符串存储在我的db;然后在从数据库检索时再次转换回。
I need to convert a List of enums values to a single string to store in my db; then convert back again when I retrieve from the database.
每个枚举的值目前是一个简单的整数,所以感觉有点过分,创建一个额外的表来处理这个。
Each enum's value is currently a simple integer, so it feels a bit overkill to create an extra table to deal with this.
所以,在下面的例子中,如果用户选择Mother,Father和Sister,那么存储在数据库中的值将是0,1,3。
So, in the example below, if the user selects Mother, Father and Sister, then the value stored in the database will be "0,1,3"
public enum MyEnum
{
Mother = 0,
Father = 1,
Gran = 2,
Sister = 3,
Brother = 4
}
所以不知道有没有一个漂亮的开箱即用的方式来做到这一点 - 我找不到任何明显的时候google狩猎!
I'm new to c#, so not sure if there is a nice out-the-box way to do this - I couldn't find anything obvious when google hunting!
提前干杯:)
- L
Cheers in advance :) - L
推荐答案
以下将通过0,1,3
The following will convert back and forth between an array of Enum values via "0,1,3" as requested:
MyEnum[] selection = { MyEnum.Mother, MyEnum.Father, MyEnum.Sister };
string str = string.Join(",", selection.Cast<int>());
MyEnum[] enm = str.Split(',').Select(s => int.Parse(s)).Cast<MyEnum>().ToArray();
这篇关于有没有一种简单的方法来一个C#枚举转换为字符串,然后再返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!