【问题标题】:How to allow “/” in then name of an enum member? [closed]如何在枚举成员的名称中允许“/”? [关闭]
【发布时间】:2020-10-09 03:43:43
【问题描述】:

如何在枚举中允许带有 / 的字符串?

 enum basePath
    {
        student/getAllStudent,
        employee/getAllEmployee
    };

示例代码感谢,谢谢

【问题讨论】:

  • 语言标准不允许这样做。所以我认为没有办法解决这个问题。你能详细说明为什么你需要在枚举中有/ 吗?
  • 你不能。您似乎正在尝试以不打算使用的方式使用枚举。
  • 在c#中命名对象时只能使用字母、数字和下划线字符。
  • 你为什么要那个?
  • @RufusL 我的意思是名称简单但值分配有/的字段...public static string Employee = "employee/getAllEmployee";

标签: c# syntax enums


【解决方案1】:

您可以使用 System.ComponentModel 命名空间中的描述属性并使枚举类似

using System.ComponentModel;
enum basePath
{
    [Description("student/getAllStudent")]
    GetAllStudent,
    [Description("employee/getAllEmployee")]
    GetAllEmployee
}

现在要访问描述,通过创建如下所示的类来添加以下帮助方法

public static class ExtensionMethod
{
    
    public static string GetDescription(this Enum GenericEnum) //Hint: Change the method signature and input paramter to use the type parameter T
    {
        Type genericEnumType = GenericEnum.GetType();
        MemberInfo[] memberInfo = genericEnumType.GetMember(GenericEnum.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            var _Attribs = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            if (_Attribs != null && _Attribs.Count() > 0)
            {
                return ((System.ComponentModel.DescriptionAttribute)_Attribs.ElementAt(0)).Description;
            }
        }
        return GenericEnum.ToString();
    }

}

现在你可以通过调用来获取描述

basePath.GetAllStudent.GetDescription();

但我的建议是使用下面这样的静态类

public static class MyPaths
{
     public static readonly string GET_ALL_STUDENT = "student/getAllStudent"; 
     public static readonly string GET_ALL_EMPLOYEES = "employee/getAllEmployees";
}

//and then use like 
MyPaths.GET_ALL_STUDENT;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多