首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将数字动态绑定到枚举

如何将数字动态绑定到枚举
EN

Stack Overflow用户
提问于 2017-12-10 08:47:17
回答 4查看 224关注 0票数 2

下面是我们如何将数字定义为enum:

代码语言:javascript
复制
enum Color
{
    Red = 1,
    Green = 2,
    Blue = 3
}

由此,数字值为const。

我想在运行时动态地分配它怎么样?还是用密码来修改?然后改变它变成这样:

代码语言:javascript
复制
enum Color
{
    Red = 4,
    Green = 8,
    Blue = 9
}

我有一种方法

代码语言:javascript
复制
Enum.BindNumber(Color.Red, 4);

解决方案:

在阅读了下面的答案/信息之后,我编写了一个自定义类来解决这个问题:

代码语言:javascript
复制
public enum SectionName
{
    UnknownSection,
    SectionA,
    SectionB,
    SectionC,
    SectionD
}

public class Section
{
    Dictionary<SectionName, int> dic = new Dictionary<SectionName, int>();

    public int SectionA { get { return dic[SectionName.SectionA]; } }
    public int SectionB { get { return dic[SectionName.SectionB]; } }
    public int SectionC { get { return dic[SectionName.SectionC]; } }
    public int SectionD { get { return dic[SectionName.SectionD]; } }

    public int this[SectionName sn]
    {
        get
        {
            if (dic.ContainsKey(sn))
                return dic[sn];
            return 0;
        }
        set
        {
            dic[sn] = value;
        }
    }

    public SectionName this[int num]
    {
        get
        {
            foreach(var kv in dic)
            {
                if (kv.Value == num)
                    return kv.Key;
            }
            return SecionName.UnknownSection;
        }
        set
        {
            dic[value] = num;
        }
    }
}

更新:背后的场景

我想回应一些反馈,并在下面的问题中被问到为什么我需要做这个Enum>>Number绑定?我将在下面解释我的情况:

伙计们,对我来说,从长远来看,改变数据库结构有点让人头疼。我觉得更改代码要比更改数据库结构容易得多。

如果对数据库结构进行分析,它将对编码部分的整体破坏产生等效的地震破坏作用。但是,您可以随时更改代码而不更改数据库。

因此,从长远来看,数据库的设计必须要有很好的形式,使其能够灵活地适应变化,并为程序版本的进化提供可持续的能力。

在我目前的新项目中..。这是自定义web cms项目。这是第一次尝试,我建立的网站只有一个表。以下是表的结构:

代码语言:javascript
复制
CREATE TABLE `item` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned DEFAULT NULL,
  `key` varchar(100) DEFAULT NULL,
  `data` mediumtext,
  `seq` int(10) unsigned DEFAULT NULL,
  `status` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

表结构

代码语言:javascript
复制
------------------------------------
Columns   | Data Type              |
------------------------------------
id        | int (auto-increment)   |
parent_id | int                    |
key       | varchar                |
data      | mediumtext             |
seq       | int                    |
status    | int                    |
------------------------------------

数据库中的第一个项目将是域项,如下所示:

第一项

代码语言:javascript
复制
id = 1 <auto-generate> first item
parent_id = 0 (this is the first item, definitely no parent
key = 'mydomainname.com'
data = null (not important at this stage)
seq = null (not important at this stage)
status = null (not important at this stage)

网站中有许多预定义的部分,例如:

  • 头版滑翔机
  • 网络编辑(用户)
  • 页脚块
  • Category1
  • Category2
  • 等等..。

每一节都将在Enum中定义。

代码语言:javascript
复制
Section            | Enum
-------------------------------------
Front Page Slider  | FrontPageSlider
Web Editors (user) | UserList
Footer Blocks      | FooterBlock
Category1          | Category1
Category2          | Category2

我使用"key"<>"data“(parent<>child)匹配方法存储所有信息,并将其存储在数据库中。

例如,:存储滑块数据

首先,创建Slider父项

代码语言:javascript
复制
id = 2 <auto-generate> 2nd item
parent_id = 1 (refers to 1st item)
key = 'FrontPageSlider'
data = null (not important at this stage)
seq = null (not important at this stage)
status = null (not important at this stage)

现在,幻灯片数据

第一幻灯片

代码语言:javascript
复制
id = 3 <auto-generate> 3rd item
parent_id = 2 (refers to 2nd item)
key = 'my_first_photo.jpg'
data = null (not important at this stage)
seq = 1 
status = 1

第二滑梯

代码语言:javascript
复制
id = 4 <auto-generate>
parent_id = 2 (refers to 2nd item)
key = 'dog_cat_running.jpg'
data = null (not important at this stage)
seq = 1 
status = 1

另一个示例:存储用户编辑器的数据

创建用户父项

代码语言:javascript
复制
id = 5 <auto-generate>
parent_id = 1 
key = 'UserList'
data = null (not important at this stage)
seq = null (not important at this stage)
status = null (not important at this stage)

第一用户:

代码语言:javascript
复制
id = 6 <auto-generate>
parent_id = 5
key = 'adam'
data = 'pwd=fa23f....2f283|salt=faff...awefw|fullname=Adam Smith
seq = null (not important at this stage)
status = 1

第二用户:

代码语言:javascript
复制
id = 7 <auto-generate>
parent_id = 5
key = 'jasmine'
data = 'pwd=0x0a2f....2f3|salt=0xfxff...afb|fullname=Jasmine Irene
seq = null (not important at this stage)
status = 1

好了,现在你知道数据是如何相互联系的了。

固定的部分将在编码中定义为Enum,但是id是在数据库中作为第二级父级自动生成的。我需要将数据库中的数字(自动递增的id)绑定到Enum,这样我就可以从数据库中获得父项,然后再子条目。

正如你们中的一些人所说,这是疯狂的尝试。是的,我完全同意你们这么疯狂。我不知道你对此有何感想,但我个人认为,这是一次非常棒的尝试,只使用一张桌子来处理所有事情:)

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-12-10 08:55:40

不,但作为一种解决办法,您可以考虑使用Dictionary

代码语言:javascript
复制
var colorsDict = new Dictionary<Color, int>() {
   {Color.Red, 4}, {Color.Green, 8}, {Color.Blue, 9}
};

您可以随时动态地更改它。

但是,显然不能将一个数字转换为枚举,并期望得到正确的结果:

代码语言:javascript
复制
(Color)8 // probably not green

即使语言确实支持上面的内容,当值可能发生变化时,这样做仍然是有问题的。你可能不小心改变了什么东西,一切都坏了。

票数 2
EN

Stack Overflow用户

发布于 2017-12-10 08:49:28

不,这是不可能的,您可以将枚举值看作常量,将名称看作“占位符”,以提高代码的可读性。在幕后,枚举只是一个结构,它有一个value__字段(数值)和几个命名值的常量。因为它们是常量,所以不能在运行时修改它们。

代码语言:javascript
复制
.class private auto ansi sealed Color extends [mscorlib]System.Enum
{
  .field public specialname rtspecialname int32 value__
  .field public static literal valuetype Color Red = int32(0x00000001)
  .field public static literal valuetype Color Green = int32(0x00000002)
  .field public static literal valuetype Color Blue= int32(0x00000003)
}
票数 1
EN

Stack Overflow用户

发布于 2017-12-14 10:48:24

我重写了你的包装纸。

代码语言:javascript
复制
    /// <summary>
    /// This class wrapps any enum and make values changeable.
    /// </summary>
    /// <typeparam name="T">Struct to be wrapped</typeparam>
    public class ChangeableEnum<T> where T : struct, IConvertible
    {
        // This dict contains all values of enum
        IDictionary<T, int> _dict;

        /// <summary>
        /// Constructor intializes with the given enum (as generic-class-type)
        /// </summary>
        public ChangeableEnum()
        {
            _dict = new Dictionary<T, int>();

            // iterate over each value and get value
            foreach (T obj in Enum.GetValues(typeof(T)))
                _dict.Add(obj, Convert.ToInt32(obj));
        }

        /// <summary>
        /// Get or set a value of enum.
        /// </summary>
        /// <param name="obj">Enum-type to get or set</param>
        /// <returns>Value of given enum-type.</returns>
        public int this[T obj]
        {
            get { return _dict[obj]; }
            set { _dict[obj] = value; }
        }
    }

这段代码未经测试,可能有一些bug。

如何使用颜色-枚举:

代码语言:javascript
复制
    public enum Color
    {
        Red = 4,
        Green = 8
    }

用一种方法

代码语言:javascript
复制
ChangeableEnum<Color> test = new ChangeableEnum<Color>();

// get
System.Diagnostics.Trace.WriteLine(test[Color.Red]);

// set
test[Color.Red] = 5436;

// get again
System.Diagnostics.Trace.WriteLine(test[Color.Red]);

但我认为,你在错误的情况下使用枚举。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47737245

复制
相关文章

相似问题

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