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

时间:2009-06-03 06:46:39

标签: c# enums casting int

我有一个名为Questions的类(复数)。在这个类中有一个名为Question(单数)的枚举,看起来像这样。

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

Questions类中,我有一个get(int foo)函数,为Questions返回foo个对象。是否有一种简单的方法可以从枚举中获取整数值,这样我可以执行Questions.Get(Question.Role)之类的操作?

31 个答案:

答案 0 :(得分:2055)

只需输入枚举,例如

int something = (int) Question.Role;

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

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

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

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;

答案 1 :(得分:275)

由于枚举可以是任何整数类型(byteintshort等),因此获取枚举的基本整数值的更强大的方法是将GetTypeCode方法与Convert类结合使用:

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

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

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

答案 2 :(得分:176)

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

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或您定义的任何内容。

答案 3 :(得分:78)

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

将导致value == 2

答案 4 :(得分:64)

在相关说明中,如果您想从int获取System.Enum值,则在此处显示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);

最后两个很难看。我更喜欢第一个。

答案 5 :(得分:37)

它比你想象的容易 - 枚举已经是一个整数。它只需要提醒:

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

答案 6 :(得分:26)

示例:

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

枚举将增加1,您可以设置起始值。如果您没有设置起始值,它最初将被指定为0。

答案 7 :(得分:20)

我最近在代码中转而使用枚举,转而使用带有受保护构造函数和预定义静态实例的类(感谢Roelof - C# Ensure Valid Enum Values - Futureproof Method)。

鉴于此,下面是我现在处理此问题的方法(包括隐式转换为/ 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表达式主体定义。有关原始代码,请参阅revision history。这样做的好处是使定义不那么冗长;这是对这个答案方法的主要抱怨之一。

答案 8 :(得分:17)

如果你想得到存储在变量中的枚举值的整数,类型为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。

我很难在互联网上找到这个简单的解决方案而我找不到它,所以我正在测试一些东西并发现了这一点。希望这可以帮助。 ;)

答案 9 :(得分:14)

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

// 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() + ".");

我希望这会有所帮助。

答案 10 :(得分:11)

也许我错过了它,但有人试过一个简单的通用扩展方法。这对我很有用。您可以通过这种方式避免API中的类型转换,但最终会导致更改类型操作。这是编程Roselyn以使编译器为您创建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;
    }
}    

答案 11 :(得分:11)

另一种方法:

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

将导致:

Name: Role, Value: 2

答案 12 :(得分:10)

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感到更舒服,因为Visual Basic可以满足许多领域的这种期望。

答案 13 :(得分:9)

int number = Question.Role.GetHashCode();

number的值应为2

答案 14 :(得分:8)

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

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();

答案 15 :(得分:7)

如何改为使用扩展方法:

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

用法稍微漂亮一点:

var intValue = Question.Role.IntValue();

答案 16 :(得分:4)

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 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);
}

答案 17 :(得分:3)

我最喜欢使用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    

<强>声明: 对于基于长

的枚举不起作用

答案 18 :(得分:3)

以下是扩展方法

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;
}

答案 19 :(得分:3)

使用:

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

答案 20 :(得分:2)

我想建议&#39;以获得&#39; int&#39;枚举的价值是,&#39;

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

int answer = (int)Sample.Book;

现在答案是1。

我希望这可以帮助别人。

答案 21 :(得分:2)

由于枚举可以用多种基本类型声明,因此用于转换任何枚举类型的通用扩展方法都很有用。

instanceof

答案 22 :(得分:1)

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

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

答案 23 :(得分:1)

我能想到的最简单的解决方案是重载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);
    }
}

答案 24 :(得分:1)

在Vb。它应该是

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

Private value As Integer = CInt(Question.Role)

答案 25 :(得分:1)

使用:

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

它将产生value == 2

仅当枚举适合放在int内时如此。

答案 26 :(得分:0)

我对游戏有点迟了,但是我想出了包括当前语言功能在内的这种扩展方法。通过使用动态,我不需要使它成为通用方法并指定使调用更简单和一致的类型。如果做错了事,请告诉我:

public static class EnumEx
{
    public static dynamic Value(this Enum e)
    {
        switch (e.GetTypeCode())
        {
        case TypeCode.Byte:
            {
                return (byte) (IConvertible) e;
            }
        case TypeCode.Int16:
            {
                return (short) (IConvertible) e;
            }
        case TypeCode.Int32:
            {
                return (int) (IConvertible) e;
            }
        case TypeCode.Int64:
            {
                return (long) (IConvertible) e;
            }
        case TypeCode.UInt16:
            {
                return (ushort) (IConvertible) e;
            }
        case TypeCode.UInt32:
            {
                return (uint) (IConvertible) e;
            }
        case TypeCode.UInt64:
            {
                return (ulong) (IConvertible) e;
            }
        case TypeCode.SByte:
            {
                return (sbyte) (IConvertible) e;
            }
        }

        return 0;
    }

答案 27 :(得分:0)

您应该已经使用Type Casting,因为我们可以使用其他任何语言。

如果您的enum是这样的-

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

您需要强制转换为int,然后执行此操作-

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

重新-

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

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

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

  • 显式投射(手动-将较大的类型转换为较小的类型,例如-

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

更多信息可以在 here 中找到。

答案 28 :(得分:0)

会给你一个包含枚举所有整数值的列表:

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

答案 29 :(得分:0)

    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 )

答案 30 :(得分:-14)

试试这个:

int value = YourEnum.ToString("D");
相关问题