【问题标题】:How to get enum Key in C# using Enum Value [duplicate]如何使用枚举值在 C# 中获取枚举键 [重复]
【发布时间】:2021-12-24 20:17:33
【问题描述】:

我有 1 个字符串变量,有 Enums,需要将传入的字符串变量与 Enum Values 进行比较,如果找到比较,我需要获取比较的 Enum Key 并分配给一些 int 变量。我怎样才能做到这一点? 我只需要枚举键。

例如我有:

public class Enums
{
  Admin = 0,
  Seller = 1,
  Member = 2,
  Unknown = 3
}

还有一些基类:

string tech = “Member”;

foreach(string value in Enum.GetNames(typesof(Enums)))
{
  If(tech == value)
{
  int enumValueKey =  And here I need '2'. 
}}}

在基类中,我只有字符串类型变量,例如(字符串管理员、字符串卖方、字符串成员、字符串未知)。如果它找到 1 个比较,则应将 Key 写入 int value ,与 Enums 中找到的值相同。

非常感谢

【问题讨论】:

  • 看看Enum.ParseEnum.TryParse
  • int key = (int) (Enum.Parse<Enums>(tech)); - 只需Parse,然后根据需要转换为int

标签: c# asp.net-core variables foreach enums


【解决方案1】:

您可以通过Enum.Parsetypeof 实现此目的

public enum Enums
{
  Admin = 0,
  Seller = 1,
  Member = 2,
  Unknown = 3
}

int myEnum = (int)(Enums)Enum.Parse(typeof(Enums), "Seller");
Console.WriteLine(myEnum); // 1

【讨论】:

  • 重要的是要提到nameof 在编译时进行评估,所以像Enums enumValue = Enums.Seller; string enumName = nameof(enumValue); 这样的东西会导致"enumValue" 而不是"Seller"
  • 谢谢,但我最终需要接受 int。 Exp: 我有字符串 a = "Member" 需要拿到他的 Key (number 2)
  • 我根据您的要求更新了我的答案@LevanAmashukeli
猜你喜欢
  • 2014-02-02
  • 1970-01-01
  • 2012-12-28
  • 2016-03-05
  • 2012-08-11
  • 2022-08-03
  • 1970-01-01
  • 2013-03-23
相关资源
最近更新 更多