我有一类称为 Questions (复数).在这一类中还有一个称为enum Question (单数),它看起来像这样。

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

Questions 类,我有一个 get(int foo) 功能即将返回 Questions 对象, foo.是有一个简单的方法来获得整数值从枚举,所以我可以做的东西喜欢 Questions.Get(Question.Role)?

有帮助吗?

解决方案

只投枚举,例如

int something = (int) Question.Role;

上述会工作的绝大多数枚举的,你看到的野,作为默认基本类型是enum int.

然而,作为 cecilphillip 所指出的,可以枚举的有不同的潜在的类型。如果一个枚举被宣布为 uint, long, 或 ulong, 它应该被铸造的类型enum;例如对于

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

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;

其他提示

由于枚举可以是任何一体类型(byte, int, short, 等等), 一个更可靠的方法来获得基本的整体价值的枚举会使用的 GetTypeCode 方法结合 Convert 级:

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

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

这应该不论的基础的整体类型。

声明它作为一个静态的类具有公共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;
}

然后你就可以参考 Question.Role, 和它的评估是一个 int 或者不管你把它定义为。

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

将会导致 value == 2.

在一个相关的注意,如果你想要得到的 intSystem.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);

最后两个普通的丑陋.我喜欢第一个。

它比你想象的要容易-一个枚举,已经是一个int.它只是需要被提醒:

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

例如:

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。

我有最近转为距离使用枚举,在我的代码赞成票,而不是采用类保护的构造和预定的静态的实例(由于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方式)而不是把很多情况下语句在你的代码,以解决每个情况。


NB:答案更新2018-04-27使用C#6功能;即宣言表达和lambda表达体定义。看看 修订历史 对于原始代码。这有利于使该定义的一个小小的详细;已经一个主要的投诉关于这个答案的方法。

如果你想要得到整数枚举的价值,是保存在一个变,这类会 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。

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

为确保一个枚举,值存在,然后分析了它,你还可以做以下。

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

我希望这有所帮助。

也许我错过它但是,有人试过一个简单的通用扩展的方法。这个伟大的作品对我来说。你可以避免的类型投在你的API这种方式,但最终结果在一个更改类型的操作。这是一个很好的情况下编程罗斯琳*具有编译器使获取名方法。

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

另一种方式来做到这一点:

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

将产生以下成果:

Name: Role, Value: 2
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 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();
int number = Question.Role.GetHashCode();

number 应该有的价值 2.

如何扩展的方法,而不是:

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

和使用量稍稍漂亮:

var intValue = Question.Role.IntValue();
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);
}

我最喜欢哈克与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    

免责声明: 不工作枚举的基础上长

下面是扩展的方法

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

由于枚举,可以声明与多种基本类型、扩展的通用方法,以铸任何枚举的类型可以是有用的。

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;

例,我谨建议得到'int'值从枚举,'

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

int answer = (int)Sample.Book;

现在,答案将是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);
    }
}

试试这个,而不是转换枚举int:

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

在Vb。它应该是

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

Private value As Integer = CInt(Question.Role)

我有点晚了游戏但是我想出了这个扩展方法,包括目前的语言的特征。通过使用动态的,我不需要做这一个通用的方法和指定的类型,保持调用更简单和一致。请让我知道如果我做错了什么:

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;
    }
Question question = Question.Role;
int value = question.GetHashCode();

将会导致 value == 2.

这只是真的,如果枚举符合内部的一个 int

试试这个:

int value = YourEnum.ToString("D");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top