【问题标题】:Enum returning int instead of string C#枚举返回 int 而不是字符串 C#
【发布时间】:2022-01-12 23:10:35
【问题描述】:

我打算在这里提取男性和女性值的枚举类

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DoB { get; set; }
    public enum MF { Male,Female }
    public MF Gender { get; set; } //here's my target
}

这里是我从数据库 msql 中提取的数据访问层

public IList<Employee> GetAllEmployees()
{
    string query = "EXEC GetAllEmployees";
    string constring = "Data Source=.\\SQLEXPRESS;Initial Catalog=ProjectDatabase;Integrated Security=True;Pooling=False";
    IList<Employee> AllEmployees = new List<Employee> {};

    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
    {
        List<Employee> customers = new List<Employee>();
        //cmd.CommandType = CommandType.Text;
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
    {
        while (sdr.Read())
       {
           AllEmployees.Add(new Employee
           {
              ID     = Convert.ToInt32(sdr["ID"]),
              Name   = sdr["Name"].ToString(),
              DoB    = (DateTime)sdr["DoB"],
              Gender = (MF)Enum.Parse(typeof(MF), (string)sdr["Gender"]), //here's where it extracts the Gender value as 0 or 1 instead in plain words
           });
                }
                    }
                    con.Close();
                    return AllEmployees;
                }
            }
        }

业务逻辑层不言自明

        public IList<Employee> GetEmployees(string name,MF gender)
        {
            EmployeeDAL EDAL = new EmployeeDAL();

            if (name == "")
                return EDAL.GetAllEmployees(); //Ignore this for now

            else
                return EDAL.GetFilteredEmployees(name,gender); //this gets used in this case
        }

一切开始的控制器层

[Route("GetEmployees")]
[HttpPost]
public IList<Employee> GetEmployees(JArray PostData)
{
   string Name = (string)PostData[0]["Name"];
   MF Gender = (MF)Enum.Parse(typeof(MF), (string)PostData[0]["Gender"]);//grabed from a post request from AngularJS code
   EmployeeBLL EBLL = new EmployeeBLL();
   return EBLL.GetEmployees(Name,Gender);
}

大家好,我想使用我的 Gender 枚举为 AngularJS POST 请求返回男性或女性,但我一直得到男性 0 和女性 1。我该如何解决? cmets 中的所有其他详细信息。

【问题讨论】:

  • 提示:如果您将enum 写入数据库,请将值分配给枚举值。 enum MF { Male = 1,Female = 2 } 任何添加(可能会)和重新排序都不会破坏向后兼容性。
  • 枚举是(当没有其他指定时)一个 int。 Enum.Parse 无法返回强类型枚举。 (你可以为它创建一个通用的扩展方法。
  • 数据库表中“性别”列的数据类型是什么?
  • 如果你有一个MF,你可以打电话给.ToString。无需铸造。遵循@the2step 所说的内容:var stringValue = MF.Male.ToString();
  • Enum.GetName(typeof(Gender), _value)

标签: c# asp.net angularjs asp.net-mvc-4


【解决方案1】:

对你来说,枚举看起来像字符串,因为它们的命名方式,但实际上它们是数字,至少根据计算机而言。您可以致电.ToString() 获取名称作为搅拌器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 2021-06-10
    • 2017-04-14
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多