简体   繁体   English

从数据库中获取整数值并将其转换为Enum

[英]Take integer value from database and cast it to Enum

I'm all new to Enum types and seems like I can't figure something out in my project. 我是Enum类型的新手,似乎无法在项目中弄清楚什么。 I was asked to use Enum for creating a combobox with pre-defined values. 我被要求使用Enum创建具有预定义值的组合框。 What I did was: 我所做的是:

namespace Models
{
    public class LastStatus
    {
        public LastStatus()
        {
        }

        public int ID { get; set; }
        public enum description { inProgress, done, accepted }

        public description desc;
        public int constant { get; set; }

    }
}

And this is my method for converting the DB model to my own model before I use them: (eg add them to a List and then iterate over it to add to the combobox's listitems in aspx.cs side) 这是我在使用数据库模型之前将其转换为我自己的模型的方法:(例如,将它们添加到列表中,然后对其进行迭代以添加到aspx.cs一侧的组合框的列表项中)

private Models.LastStatus ConvertStatusDbToObject(DBModel.myDB.LastStatu status)
        {
            Models.LastStatus statusObject = new Models.LastStatus();
            statusObject.ID = status.ID;
            //statusObject.description = status.description;
            (LastStatus.description)statusObject.desc = (LastStatus.description)status.@const;
            statusObject.constant = status.@const;

            return statusObject;
        }

I get the error on this line: 我在这条线上收到错误:

(LastStatus.description)statusObject.desc = (LastStatus.description)status.@const;

when trying to cast the integer value of the DB Model to my enum type. 尝试将数据库模型的整数值转换为我的枚举类型时。 Isn't desc a property? 是不是desc的属性?

Error 23 The left-hand side of an assignment must be a variable, property or indexer 错误23分配的左侧必须是变量,属性或索引器

Change (LastStatus.description)statusObject.desc = (LastStatus.description)status.@const; 更改(LastStatus.description)statusObject.desc = (LastStatus.description)status.@const; to statusObject.desc = (LastStatus.description)status.@const; statusObject.desc = (LastStatus.description)status.@const;

You don't need to cast the property itself! 您不需要强制转换属性!

First , assign integer values to your enum values when declaring the enum. 首先 ,在声明枚举时将整数值分配给您的枚举值。 for example: 例如:

public enum description { inProgress = 0, done = 1, accepted = 2}

Second , I would recommend against having public fields in your class. 其次 ,我建议您不要在课堂上使用公共领域。 change 更改

public description desc;

to

public description desc { get; set; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM