首页 > 解决方案 > 有没有办法使用单个字符获取枚举的字符串值?

问题描述

我在 MVC 应用程序中使用一个枚举,它看起来像下面的枚举,

public enum School
{
    DVB=1,
    AVD=2,
    ASB=3
}

而且我从每所学校的数据库中获取了唯一的单个字符,例如:

D for DVB
A for AVD
B for ASB

我想打印枚举值的全名。我可以通过以下方式实现我的目标,即我可以编辑枚举并按字符替换枚举的整数值。但我认为这不是一个好的解决方案,因为现有代码也使用整数值。

有没有其他方法可以使用单个字符获取枚举的字符串值?

标签: c#enums

解决方案


最干净的方法是与您的团队坐在一起计划并接受迁移您的数据库并存储一个整数值。

无论如何,根据您在问题中的评论,您正在使用实体框架并将您的实体映射到视图模型。以下步骤可以帮助您无需反思,添加新属性或新枚举。

假设您正在使用一个名为 MyEntitycontains 的实体,该实体实际上包含一个名为 的属性MySchool

首先不是使用School枚举作为类型MySchool属性,而是使用字符串类型。因此 EF 只会从数据库中检索数据并将其直接放入属性中。无需转换。所以你会有这样的东西:

public class MyEntity
{
    public string MySchool { get; set; }
}

其次,总是在你的MyEntity类中添加另一个属性,让它命名MySchoolEnum为枚举类型School,而不是映射到数据库,这样你就有了:

[NotMapped] // <-- This tell EF that this property is not mapped to the database.
public School? MyShcoolEnum
{
    get
    {
        // Getting the value of this property depends on the value of the database
        // which is stored into MySchool property.
        switch (MySchool)
        {
            case "D": return School.DVB;
            case "A": return School.AVD;
            case "B": return School.ASB;
            default: return null;
        }
    }

    set
    {
        // When setting this property 
        // you automatically update the value of MySchool property
        switch (value)
        {
            case School.DVB: this.MySchool = "D";
                break;
            case School.AVD: this.MySchool = "A";
                break;
            case School.ASB: this.MySchool = "B";
                break;
            default: this.MySchool = null;
                break;
        }
    }
}

旁注:使用 EF Core 有一种更优雅的方式来执行此类操作,而无需添加新属性。使用 EF Core 2.1,我们可以摆脱这个属性并使用Value Conversion

最后,所有需要处理MySchool数据库列的视图模型不应该使用MySchool属性,而是将其对应的属性映射到MyShcoolEnum您的实体的属性。

您的实体代码应与此类似:

public class MyEntity
{
    public string MySchool { get; set; }

    [NotMapped] // <-- This tell EF that this property is not mapped to the database.
    public School? MyShcoolEnum
    {
        get
        {
            // Getting the value of this property depends on the value of the database
            // which is stored into MySchool property.
            switch (MySchool)
            {
                case "D": return School.DVB;
                case "A": return School.AVD;
                case "B": return School.ASB;
                default: return null;
            }
        }

        set
        {
            // When setting this property you automatically update the value of MySchool property
            switch (value)
            {
                case School.DVB: this.MySchool = "D";
                    break;
                case School.AVD: this.MySchool = "A";
                    break;
                case School.ASB: this.MySchool = "B";
                    break;
                default: this.MySchool = null;
                    break;
            }
        }
    }
}

推荐阅读