从 C# 中的枚举中获取 int 值

发布于 2024-07-22 04:19:12 字数 463 浏览 10 评论 0原文

我有一个名为 Questions (复数)的课程。 在这个类中,有一个名为 Question (单数)的枚举,如下所示。

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

Questions 类中,我有一个 get(int foo) 函数,它返回该 fooQuestions 对象。 有没有一种简单的方法可以从枚举中获取整数值,以便我可以执行类似 Questions.Get(Question.Role) 的操作?

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

In the Questions class I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value off the enum so I can do something like this Questions.Get(Question.Role)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

感情洁癖 2024-07-29 04:19:12

只需转换枚举,例如

int something = (int) Question.Role;

上面的内容适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是int

但是,正如 cecilphillip 指出的那样,枚举可以具有不同的基础类型。
如果枚举被声明为 uintlongulong,则应将其强制转换为枚举的类型; 例如

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;

Just cast the enum, e.g.

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

long something = (long)StarsInMilkyWay.Wolf424B;
梦开始←不甜 2024-07-29 04:19:12

由于枚举可以是任何整数类型(byteintshort 等),因此有一种更可靠的方法来获取底层整数值枚举将结合使用 GetTypeCode 方法和 Convert 类:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

无论底层整数类型如何,这都应该有效。

Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

This should work regardless of the underlying integral type.

山田美奈子 2024-07-29 04:19:12

将其声明为具有公共常量的静态类:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

然后您可以将其引用为 Question.Role,并且它的计算结果始终为 int 或您将其定义为的任何内容。

Declare it as a static class having public constants:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

And then you can reference it as Question.Role, and it always evaluates to an int or whatever you define it as.

一身软味 2024-07-29 04:19:12

说明,如果您想从 System.Enum 获取 int 值,则在此处给出 e

Enum e = Question.Role;

您可以使用:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

相关 两个简直丑陋。 我更喜欢第一个。

On a related note, if you want to get the int value from System.Enum, then given e here:

Enum e = Question.Role;

You can use:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

The last two are plain ugly. I prefer the first one.

伤痕我心 2024-07-29 04:19:12
Question question = Question.Role;
int value = (int) question;

将导致 value == 2

Question question = Question.Role;
int value = (int) question;

Will result in value == 2.

趁年轻赶紧闹 2024-07-29 04:19:12

示例:

public enum EmpNo
{
    Raj = 1,
    Rahul,
    Priyanka
}

并在后面的代码中获取枚举值:

int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1

否则

int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2

Enums将增加1,并且可以设置起始值。 如果您不设置起始值,它将最初被指定为 0。

Example:

public enum EmpNo
{
    Raj = 1,
    Rahul,
    Priyanka
}

And in the code behind to get the enum value:

int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1

or

int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2

Enums will increment by 1, and you can set the start value. If you don't set the start value it will be assigned as 0 initially.

↙厌世 2024-07-29 04:19:12

这比你想象的要容易——枚举已经是整数了。 只是需要提醒的是:

int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2

It's easier than you think - an enum is already an int. It just needs to be reminded:

int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2
恍梦境° 2024-07-29 04:19:12

我最近不再在代码中使用枚举,而是使用带有受保护构造函数和预定义静态实例的类(感谢 Roelof - C# 确保有效的枚举值 - 面向未来的方法)。

鉴于此,下面是我现在解决此问题的方法(包括与 int 之间的隐式转换)。

public class Question
{
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
    {
        this.index = index;
        this.name = name;
        values.Add(index, this);
    }

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>
        this.name;

    public static implicit operator string(Question question) =>
        question?.ToString();

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));


    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)
}

这种方法的优点是您可以从枚举中获得所有内容,但您的代码现在更加灵活,因此如果您需要根据 Question 的值执行不同的操作,您可以将逻辑放入 Question 本身(即以首选的 OO 方式),而不是在代码中放置大量 case 语句来处理每个场景。


注意:答案于 2018-04-27 更新,以利用 C# 6 功能; 即声明表达式和 lambda 表达式主体定义。 请参阅修订历史记录了解原始代码。 这样做的好处是使定义不那么冗长; 这是对此答案方法的主要抱怨之一。

I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).

In light of that, below's how I'd now approach this issue (including implicit conversion to/from int).

public class Question
{
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
    {
        this.index = index;
        this.name = name;
        values.Add(index, this);
    }

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>
        this.name;

    public static implicit operator string(Question question) =>
        question?.ToString();

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));


    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)
}

The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of Question, you can put logic into Question itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.


NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.

白况 2024-07-29 04:19:12

如果您想获取存储在变量中的枚举值的整数(其类型为 Question),以便在方法中使用,您可以简单地执行我在本文中编写的操作示例:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

这会将窗口标题更改为 4,因为变量 GeselecteerdTalen.Nederlands。 如果我将其更改为 Talen.Portugees 并再次调用该方法,文本将更改为 3。

If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question, to use for example in a method, you can simply do this I wrote in this example:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

This will change the window title to 4, because the variable Geselecteerd is Talen.Nederlands. If I change it to Talen.Portugees and call the method again, the text will change to 3.

筑梦 2024-07-29 04:19:12

使用扩展方法代替:

public static class ExtensionMethods
{
    public static int IntValue(this Enum argEnum)
    {
        return Convert.ToInt32(argEnum);
    }
}

并且用法稍微漂亮一些:

var intValue = Question.Role.IntValue();

Use an extension method instead:

public static class ExtensionMethods
{
    public static int IntValue(this Enum argEnum)
    {
        return Convert.ToInt32(argEnum);
    }
}

And the usage is slightly prettier:

var intValue = Question.Role.IntValue();
完美的未来在梦里 2024-07-29 04:19:12

另一种方法:

Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);

它将导致:

Name: Role, Value: 2

One more way to do it:

Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);

It will result in:

Name: Role, Value: 2
独木成林 2024-07-29 04:19:12

要确保枚举值存在并解析它,您还可以执行以下操作。

// Fake Day of Week
string strDOWFake = "SuperDay";

// Real Day of Week
string strDOWReal = "Friday";

// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
    // This will never be reached since "SuperDay"
    // doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");

To ensure an enum value exists and then parse it, you can also do the following.

// Fake Day of Week
string strDOWFake = "SuperDay";

// Real Day of Week
string strDOWReal = "Friday";

// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
    // This will never be reached since "SuperDay"
    // doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");
温折酒 2024-07-29 04:19:12

使用:

Question question = Question.Role;
int value = question.GetHashCode();

它将产生value == 2

仅当枚举适合 int 时,这才是正确的。

Use:

Question question = Question.Role;
int value = question.GetHashCode();

It will result in value == 2.

This is only true if the enum fits inside an int.

落在眉间の轻吻 2024-07-29 04:19:12
public enum QuestionType
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

……这是一个很好的声明。

您必须像这样将结果转换为 int:

int Question = (int)QuestionType.Role

否则,类型仍然是 QuestionType

这种严格程度是 C# 的方式。

一种替代方法是使用类声明:

public class QuestionType
{
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6
}

声明不太优雅,但您不需要在代码中对其进行强制转换:

int Question = QuestionType.Role

或者,您可能更喜欢使用 Visual Basic,它在许多领域满足了这种类型的期望。

public enum QuestionType
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

...is a fine declaration.

You do have to cast the result to int like so:

int Question = (int)QuestionType.Role

Otherwise, the type is still QuestionType.

This level of strictness is the C# way.

One alternative is to use a class declaration instead:

public class QuestionType
{
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6
}

It's less elegant to declare, but you don't need to cast it in code:

int Question = QuestionType.Role

Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.

眼波传意 2024-07-29 04:19:12

也许我错过了,但是有人尝试过简单的通用扩展方法吗?

这对我来说非常有用。 您可以通过这种方式避免 API 中的类型转换,但最终会导致更改类型操作。 这是一个很好的例子,可以对 Roslyn 进行编程,让编译器生成 GetValue。 方法给你。

    public static void Main()
    {
        int test = MyCSharpWrapperMethod(TestEnum.Test1);

        Debug.Assert(test == 1);
    }

    public static int MyCSharpWrapperMethod(TestEnum customFlag)
    {
        return MyCPlusPlusMethod(customFlag.GetValue<int>());
    }

    public static int MyCPlusPlusMethod(int customFlag)
    {
        // Pretend you made a PInvoke or COM+ call to C++ method that require an integer
        return customFlag;
    }

    public enum TestEnum
    {
        Test1 = 1,
        Test2 = 2,
        Test3 = 3
    }
}

public static class EnumExtensions
{
    public static T GetValue<T>(this Enum enumeration)
    {
        T result = default(T);

        try
        {
            result = (T)Convert.ChangeType(enumeration, typeof(T));
        }
        catch (Exception ex)
        {
            Debug.Assert(false);
            Debug.WriteLine(ex);
        }

        return result;
    }
}

Maybe I missed it, but has anyone tried a simple generic extension method?

This works great for me. You can avoid the type cast in your API this way but ultimately it results in a change type operation. This is a good case for programming Roslyn to have the compiler make a GetValue<T> method for you.

    public static void Main()
    {
        int test = MyCSharpWrapperMethod(TestEnum.Test1);

        Debug.Assert(test == 1);
    }

    public static int MyCSharpWrapperMethod(TestEnum customFlag)
    {
        return MyCPlusPlusMethod(customFlag.GetValue<int>());
    }

    public static int MyCPlusPlusMethod(int customFlag)
    {
        // Pretend you made a PInvoke or COM+ call to C++ method that require an integer
        return customFlag;
    }

    public enum TestEnum
    {
        Test1 = 1,
        Test2 = 2,
        Test3 = 3
    }
}

public static class EnumExtensions
{
    public static T GetValue<T>(this Enum enumeration)
    {
        T result = default(T);

        try
        {
            result = (T)Convert.ChangeType(enumeration, typeof(T));
        }
        catch (Exception ex)
        {
            Debug.Assert(false);
            Debug.WriteLine(ex);
        }

        return result;
    }
}
贵在坚持 2024-07-29 04:19:12
int number = Question.Role.GetHashCode();

number 的值应为 2

int number = Question.Role.GetHashCode();

number should have the value 2.

小…楫夜泊 2024-07-29 04:19:12

您可以通过对定义的枚举类型实施扩展方法来实现此目的:

public static class MyExtensions
{
    public static int getNumberValue(this Question questionThis)
    {
        return (int)questionThis;
    }
}

这简化了获取 int当前枚举值的值:

Question question = Question.Role;
int value = question.getNumberValue();

int value = Question.Role.getNumberValue();

You can do this by implementing an extension method to your defined enum type:

public static class MyExtensions
{
    public static int getNumberValue(this Question questionThis)
    {
        return (int)questionThis;
    }
}

This simplifies getting the int value of the current enum value:

Question question = Question.Role;
int value = question.getNumberValue();

or

int value = Question.Role.getNumberValue();
薄荷港 2024-07-29 04:19:12
public enum Suit : int
{
    Spades = 0,
    Hearts = 1,
    Clubs = 2,
    Diamonds = 3
}

Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));

// From int
Console.WriteLine((Suit)1);

// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));

if (typeof(Suit).IsEnumDefined("Spades"))
{
    var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
    Console.Out.WriteLine("{0}", res);
}
public enum Suit : int
{
    Spades = 0,
    Hearts = 1,
    Clubs = 2,
    Diamonds = 3
}

Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));

// From int
Console.WriteLine((Suit)1);

// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));

if (typeof(Suit).IsEnumDefined("Spades"))
{
    var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
    Console.Out.WriteLine("{0}", res);
}
梦在夏天 2024-07-29 04:19:12

由于可以使用多个基元类型来声明枚举,因此用于转换任何枚举类型的通用扩展方法可能会很有用。

enum Box
{
    HEIGHT,
    WIDTH,
    DEPTH
}

public static void UseEnum()
{
    int height = Box.HEIGHT.GetEnumValue<int>();
    int width = Box.WIDTH.GetEnumValue<int>();
    int depth = Box.DEPTH.GetEnumValue<int>();
}

public static T GetEnumValue<T>(this object e) => (T)e;

Since enums can be declared with multiple primitive types, a generic extension method to cast any enum type can be useful.

enum Box
{
    HEIGHT,
    WIDTH,
    DEPTH
}

public static void UseEnum()
{
    int height = Box.HEIGHT.GetEnumValue<int>();
    int width = Box.WIDTH.GetEnumValue<int>();
    int depth = Box.DEPTH.GetEnumValue<int>();
}

public static T GetEnumValue<T>(this object e) => (T)e;
葮薆情 2024-07-29 04:19:12

您应该使用类型转换 正如我们可以在任何其他语言中使用的那样。

如果您的 enum 是这样的 -

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

并且您需要转换为 int,然后执行此操作

Question q = Question.Role;
.............
.............
int something = (int) q;

-

在 C# 中,有两种类型的转换:

  • 隐式转换转换(自动 - 将较小的类型转换为较大的类型尺寸,例如 -

字符 -> int -> -> 浮动 ->

  • 显式转换(手动 - 将较大类型转换为较小尺寸类型,例如 -

-> 浮动 -> -> int -> 字符

更多信息请参见此处

You should have used Type Casting as we can use in any other language.

If your enum is like this-

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

And you need to cast to an int, then do this-

Question q = Question.Role;
.............
.............
int something = (int) q;

Re-

In C#, there are two types of casting:

  • Implicit Casting (automatically) - converting a smaller type to a larger type size like-

char -> int -> long -> float -> double

  • Explicit Casting (manually) - converting a larger type to a smaller size type like-

double -> float -> long -> int -> char

More can be found in here.

装迷糊 2024-07-29 04:19:12

我能想到的最简单的解决方案是重载 Get(int) 方法,如下所示:

[modifiers] Questions Get(Question q)
{
    return Get((int)q);
}

其中 [modifiers] 通常可以与 Get(int) 相同方法。 如果您无法编辑 Questions 类或由于某种原因不想编辑,您可以通过编写扩展来重载该方法:

public static class Extensions
{
    public static Questions Get(this Questions qs, Question q)
    {
        return qs.Get((int)q);
    }
}

The easiest solution I can think of is overloading the Get(int) method like this:

[modifiers] Questions Get(Question q)
{
    return Get((int)q);
}

where [modifiers] can generally be same as for the Get(int) method. If you can't edit the Questions class or for some reason don't want to, you can overload the method by writing an extension:

public static class Extensions
{
    public static Questions Get(this Questions qs, Question q)
    {
        return qs.Get((int)q);
    }
}
难得心□动 2024-07-29 04:19:12

我最喜欢的使用 int 或更小的枚举的技巧:

GetHashCode();

对于枚举

public enum Test
{
    Min = Int32.MinValue,
    One = 1,
    Max = Int32.MaxValue,
}

var values = Enum.GetValues(typeof(Test));

foreach (var val in values)
{
    Console.WriteLine(val.GetHashCode());
    Console.WriteLine(((int)val));
    Console.WriteLine(val);
}

输出

one
1
1
max
2147483647
2147483647
min
-2147483648
-2147483648

免责声明:

它不适用于基于 long 的枚举。

My favourite hack with int or smaller enums:

GetHashCode();

For an enum

public enum Test
{
    Min = Int32.MinValue,
    One = 1,
    Max = Int32.MaxValue,
}

This,

var values = Enum.GetValues(typeof(Test));

foreach (var val in values)
{
    Console.WriteLine(val.GetHashCode());
    Console.WriteLine(((int)val));
    Console.WriteLine(val);
}

outputs

one
1
1
max
2147483647
2147483647
min
-2147483648
-2147483648

Disclaimer:

It doesn't work for enums based on long.

凉城已无爱 2024-07-29 04:19:12

我想建议的例子是“从枚举中获取‘int’值”,

public enum Sample
{
    Book = 1, 
    Pen = 2, 
    Pencil = 3
}

int answer = (int)Sample.Book;

现在答案是 1。

The example I would like to suggest "to get an 'int' value from an enum", is

public enum Sample
{
    Book = 1, 
    Pen = 2, 
    Pencil = 3
}

int answer = (int)Sample.Book;

Now the answer will be 1.

时光礼记 2024-07-29 04:19:12

尝试这个而不是将 enum 转换为 int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}

Try this one instead of convert enum to int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}
沙与沫 2024-07-29 04:19:12

下面是扩展方法

public static string ToEnumString<TEnum>(this int enumValue)
{
    var enumString = enumValue.ToString();
    if (Enum.IsDefined(typeof(TEnum), enumValue))
    {
        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
    }
    return enumString;
}

Following is the extension method

public static string ToEnumString<TEnum>(this int enumValue)
{
    var enumString = enumValue.ToString();
    if (Enum.IsDefined(typeof(TEnum), enumValue))
    {
        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
    }
    return enumString;
}
苦笑流年记忆 2024-07-29 04:19:12

在 Visual Basic 中,它应该是:

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)

In Visual Basic, it should be:

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)
源来凯始玺欢你 2024-07-29 04:19:12

将为您提供一个包含枚举的所有整数值的列表:

List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();

will give you the a list with all the integer values of the enum :

List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();

半透明的墙 2024-07-29 04:19:12
public enum ViewType
{
    List = 1,
    Table = 2,
};
            
// You can use the Enum type as a parameter, so any enumeration from any enumerator 
// cshtml
// using proyects.Helpers
// @if (Model.ViewType== (int)<variable>.List )
public enum ViewType
{
    List = 1,
    Table = 2,
};
            
// You can use the Enum type as a parameter, so any enumeration from any enumerator 
// cshtml
// using proyects.Helpers
// @if (Model.ViewType== (int)<variable>.List )
弥枳 2024-07-29 04:19:12

几乎所有当前答案都在目标类型之前使用 Convert 或强制转换为对象,这会导致装箱和拆箱操作。 这会导致堆分配,并且对于热路径来说可能不可接受。

由于大部分答案都是书面的,System.Runtime.CompilerServices.Unsafe,支持对指针的低级操作。

与泛型相结合,Unsafe 类允许我们安全地更改 System.Enum 参数的基础类型,零分配,并且性能与空方法持续时间:

public long GetEnumValue<T>(T enumInstance) where T : unmanaged, Enum
{
    var size = Unsafe.SizeOf<T>();
    
    if (size == Unsafe.SizeOf<byte>())
    {
        return Unsafe.As<T, byte>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<short>())
    {
        return Unsafe.As<T, short>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<int>())
    {
        return Unsafe.As<T, int>(ref enumInstance); 
    }
    else if (size == Unsafe.SizeOf<long>())
    {
        return Unsafe.As<T, long>(ref enumInstance);
    }
    
    return -1; // or throw if you prefer
}

Convert vs Unsafe benchmark


如果最好始终返回 int,则可以这样做,但如果枚举的支持字段超过 int.MaxValue,则会溢出:

public int GetEnumValue<T>(T enumInstance) where T : unmanaged, Enum
{
    var size = Unsafe.SizeOf<T>();
    
    if (size == Unsafe.SizeOf<byte>())
    {
        return Unsafe.As<T, byte>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<short>())
    {
        return Unsafe.As<T, short>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<int>())
    {
        return Unsafe.As<T, int>(ref enumInstance); 
    }
    else if (size == Unsafe.SizeOf<long>())
    {
        return Unsafe.As<T, int>(ref enumInstance);
    }
    
    return -1; // or throw if you prefer
}

如果使用以下内容:

public enum EnumLong : long
{
    First,
    Second,
    Third = (long)(int.MaxValue) + 1
}

var val = GetEnumValue(EnumLong.Third);

-2147483648将由于溢出而返回。 开发人员极不可能创建具有如此大标志值的枚举,但总是有可能的。

Nearly all of the current answers use Convert or cast to object before the target type, which results in boxing and unboxing operations. This causes heap allocations and may not be acceptable for hot paths.

Since the majority of these answers were written, System.Runtime.CompilerServices.Unsafe was introduced, enabling low-level manipulation of pointers.

In combination with generics, the Unsafe class allows us to change the underlying type of the System.Enum parameter safely, with zero allocations, and with performance that is nearly indistinguishable from an empty method duration:

public long GetEnumValue<T>(T enumInstance) where T : unmanaged, Enum
{
    var size = Unsafe.SizeOf<T>();
    
    if (size == Unsafe.SizeOf<byte>())
    {
        return Unsafe.As<T, byte>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<short>())
    {
        return Unsafe.As<T, short>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<int>())
    {
        return Unsafe.As<T, int>(ref enumInstance); 
    }
    else if (size == Unsafe.SizeOf<long>())
    {
        return Unsafe.As<T, long>(ref enumInstance);
    }
    
    return -1; // or throw if you prefer
}

Convert vs Unsafe benchmark


If it is preferable to always return an int, you can do so, although if the backing field of the enum exceeds int.MaxValue, it will overflow:

public int GetEnumValue<T>(T enumInstance) where T : unmanaged, Enum
{
    var size = Unsafe.SizeOf<T>();
    
    if (size == Unsafe.SizeOf<byte>())
    {
        return Unsafe.As<T, byte>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<short>())
    {
        return Unsafe.As<T, short>(ref enumInstance);
    }
    else if (size == Unsafe.SizeOf<int>())
    {
        return Unsafe.As<T, int>(ref enumInstance); 
    }
    else if (size == Unsafe.SizeOf<long>())
    {
        return Unsafe.As<T, int>(ref enumInstance);
    }
    
    return -1; // or throw if you prefer
}

If the following were used:

public enum EnumLong : long
{
    First,
    Second,
    Third = (long)(int.MaxValue) + 1
}

var val = GetEnumValue(EnumLong.Third);

-2147483648 would be returned due to an overflow. It is extremely unlikely that developers would create enums with such large flag values, but is always a possibility.

云裳 2024-07-29 04:19:12

我正在遵循这种方法来访问 Enums 的值

public class Enum<TEnum> where TEnum : Enum
     {
    
         public static string[] ToArray()
         {
             return Enum.GetValues(typeof(TEnum))
                .Cast<TEnum>()
                .ToList()
                .Select(c => c.ToString())
                .ToArray();
         }
         public static List<EnumValues> ToList()
         {
             return Enum.GetValues(typeof(TEnum))
               .Cast<TEnum>()
               .ToList()
               .Select(c => new EnumValues((int)(object)c, c.ToString()))
               .ToList();
    
         }
     }
     public class EnumValues
     {
         public int key { get; set; }
         public string value { get; set; } = string.Empty;
    
         public EnumValues(int _key, string _value)
         {
             key = _key;
             value = _value;
         }
     }
    
   

并使用此方法调用

Enum<MyEnum>.ToList()

,或者,您可以通过以下方式将枚举值返回为 int

(int)MyEnum.Value;

I'm following this approach to access the value of Enums

public class Enum<TEnum> where TEnum : Enum
     {
    
         public static string[] ToArray()
         {
             return Enum.GetValues(typeof(TEnum))
                .Cast<TEnum>()
                .ToList()
                .Select(c => c.ToString())
                .ToArray();
         }
         public static List<EnumValues> ToList()
         {
             return Enum.GetValues(typeof(TEnum))
               .Cast<TEnum>()
               .ToList()
               .Select(c => new EnumValues((int)(object)c, c.ToString()))
               .ToList();
    
         }
     }
     public class EnumValues
     {
         public int key { get; set; }
         public string value { get; set; } = string.Empty;
    
         public EnumValues(int _key, string _value)
         {
             key = _key;
             value = _value;
         }
     }
    
   

and to use this method call

Enum<MyEnum>.ToList()

or, you can return the enum value as int by

(int)MyEnum.Value;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文