I have a class called Questions
(plural). In this class there is an enum called Question
(singular) which looks like this.
我有一个名为Questions(复数)的课程。在这个类中有一个名为Question(singular)的枚举,看起来像这样。
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 from the enum so I can do something like Questions.Get(Question.Role)
?
在Questions类中,我有一个get(int foo)函数,它返回该foo的Questions对象。有没有一种简单的方法从枚举中获取整数值,所以我可以做一些像Questions.Get(Question.Role)的东西?
25 个解决方案
#1
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
.
上面的内容适用于你在野外看到的绝大多数枚举,因为枚举的默认底层类型是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
但是,正如cecilphillip所指出的,枚举可以有不同的底层类型。如果将枚举声明为uint,long或ulong,则应将其强制转换为枚举的类型;例如对于
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
你应该使用
long something = (long)StarsInMilkyWay.Wolf424B;
#2
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:
由于Enums可以是任何整数类型(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);
This should work regardless of the underlying integral type.
无论底层整数类型如何,这都应该有效。
#3
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.
然后你可以将它作为Question.Role引用,并且它总是计算为int或你定义的任何东西。
#4
Question question = Question.Role;
int value = (int) question;
Will result in value == 2
.
将导致值== 2。
#5
On a related note, if you want to get the int
value from System.Enum
, then given e
here:
在相关的说明中,如果要从System.Enum获取int值,则在此处给出e:
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.
最后两个是丑陋的。我更喜欢第一个。
#6
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
#7
Example:
public Enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
And in the code behind to get 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.
枚举将增加1,您可以设置起始值。如果未设置起始值,则最初将其指定为0。
#8
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).
我最近在代码中转而使用枚举,转而使用带有受保护构造函数和预定义静态实例的类(感谢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
).
鉴于此,下面是我现在如何解决这个问题(包括隐式转换为/来自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.
这种方法的优点是你可以从枚举中获得所有内容,但是你的代码现在更加灵活,所以如果你需要根据Question的值执行不同的操作,你可以将逻辑放入Question本身(即首选OO方式)而不是在整个代码中放置大量case语句来处理每个场景。
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.
注意:答案更新2018-04-27以利用C#6功能;即声明表达式和lambda表达式主体定义。查看原始代码的修订历史记录。这样做的好处是使定义不那么冗长;这是对这个答案方法的主要抱怨之一。
#9
If you want to get an integer for the enum value that is stored in a variable, wich the type would be Question
, to use for example in a method, you can simply do this I wrote in this example:
如果你想得到存储在变量中的枚举值的整数,那么类型将是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();
}
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.
这会将窗口标题更改为4,因为变量Geselecteerd是Talen.Nederlands。如果我将其更改为Talen.Portugees并再次调用该方法,则文本将更改为3。
I had a hard time finding this simple solution on the internet and I couldn't find it, so I was testing something and found this out. Hope this helps. ;)
我很难在互联网上找到这个简单的解决方案而我找不到它,所以我正在测试一些东西并发现了这一点。希望这可以帮助。 ;)
#10
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() + ".");
I hope this helps.
我希望这有帮助。
#11
One more way to do it:
还有一种方法:
Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);
Will result in:
将导致:
Name: Role, Value: 2
#12
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 Roselyn to have the compiler make a GetValue method for you.
也许我错过了它,但有人试过一个简单的通用扩展方法。这对我很有用。您可以通过这种方式避免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;
}
}
#13
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:
int Question = (int)QuestionType.Role
Otherwise, the type is still QuestionType
.
否则,类型仍为QuestionType。
This level of strictness is the C# way.
这种严格程度是C#方式。
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.
或者,您可能会对Visual Basic感到更舒服,因为Visual Basic可以满足许多领域的这种期望。
#14
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 simplify getting int value of current enum value:
这简化了获取当前枚举值的int值:
Question question = Question.Role;
int value = question.getNumberValue();
or
int value = Question.Role.getNumberValue();
#15
int number = Question.Role.GetHashCode();
number
should have the value 2
.
number应该具有值2。
#16
How about a 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();
#17
My fav hack with int or smaller enums:
我最喜欢使用int或更小的枚举:
GetHashCode();
For a 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: Doesn't work for enums based on long
免责声明:不适用于基于long的枚举
#18
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);
}
#19
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;
}
#20
The example I would like to suggest 'to get 'int' value from enum is,'
我想建议'从enum获得'int'值的例子是,'
public enum Sample
{Book =1, Pen=2, Pencil =3}
int answer = (int)Sample.Book;
now the answer will be 1.
现在的答案是1。
I hope this might help someone.
我希望这可能对某人有所帮助。
#21
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;
#22
The easiest solution I can think of is overloading the Get(int)
method like this:
我能想到的最简单的解决方案是重载Get(int)方法,如下所示:
[modifiers] Questions Get(Question q)
{
return Get((int)q);
}
where [modifiers]
can generally be same as for 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:
其中[modifiers]通常可以与Get(int)方法相同。如果您无法编辑Questions类或由于某种原因不想编辑,您可以通过编写扩展来重载该方法:
public static class Extensions
{
public static Questions Get(this Questions qs, Question q)
{
return qs.Get((int)q);
}
}
#23
Try this one instead of convert enum to int:
尝试这个而不是将枚举转换为int:
public static class ReturnType
{
public static readonly int Success = 1;
public static readonly int Duplicate = 2;
public static readonly int Error = -1;
}
#24
In Vb. It should be
在Vb。它应该是
Public Enum Question
Role = 2
ProjectFunding = 3
TotalEmployee = 4
NumberOfServers = 5
TopBusinessConcern = 6
End Enum
Private value As Integer = CInt(Question.Role)
#25
Try this :
试试这个 :
int value = YourEnum.ToString("D");
#1
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
.
上面的内容适用于你在野外看到的绝大多数枚举,因为枚举的默认底层类型是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
但是,正如cecilphillip所指出的,枚举可以有不同的底层类型。如果将枚举声明为uint,long或ulong,则应将其强制转换为枚举的类型;例如对于
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
你应该使用
long something = (long)StarsInMilkyWay.Wolf424B;
#2
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:
由于Enums可以是任何整数类型(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);
This should work regardless of the underlying integral type.
无论底层整数类型如何,这都应该有效。
#3
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.
然后你可以将它作为Question.Role引用,并且它总是计算为int或你定义的任何东西。
#4
Question question = Question.Role;
int value = (int) question;
Will result in value == 2
.
将导致值== 2。
#5
On a related note, if you want to get the int
value from System.Enum
, then given e
here:
在相关的说明中,如果要从System.Enum获取int值,则在此处给出e:
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.
最后两个是丑陋的。我更喜欢第一个。
#6
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
#7
Example:
public Enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
And in the code behind to get 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.
枚举将增加1,您可以设置起始值。如果未设置起始值,则最初将其指定为0。
#8
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).
我最近在代码中转而使用枚举,转而使用带有受保护构造函数和预定义静态实例的类(感谢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
).
鉴于此,下面是我现在如何解决这个问题(包括隐式转换为/来自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.
这种方法的优点是你可以从枚举中获得所有内容,但是你的代码现在更加灵活,所以如果你需要根据Question的值执行不同的操作,你可以将逻辑放入Question本身(即首选OO方式)而不是在整个代码中放置大量case语句来处理每个场景。
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.
注意:答案更新2018-04-27以利用C#6功能;即声明表达式和lambda表达式主体定义。查看原始代码的修订历史记录。这样做的好处是使定义不那么冗长;这是对这个答案方法的主要抱怨之一。
#9
If you want to get an integer for the enum value that is stored in a variable, wich the type would be Question
, to use for example in a method, you can simply do this I wrote in this example:
如果你想得到存储在变量中的枚举值的整数,那么类型将是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();
}
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.
这会将窗口标题更改为4,因为变量Geselecteerd是Talen.Nederlands。如果我将其更改为Talen.Portugees并再次调用该方法,则文本将更改为3。
I had a hard time finding this simple solution on the internet and I couldn't find it, so I was testing something and found this out. Hope this helps. ;)
我很难在互联网上找到这个简单的解决方案而我找不到它,所以我正在测试一些东西并发现了这一点。希望这可以帮助。 ;)
#10
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() + ".");
I hope this helps.
我希望这有帮助。
#11
One more way to do it:
还有一种方法:
Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);
Will result in:
将导致:
Name: Role, Value: 2
#12
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 Roselyn to have the compiler make a GetValue method for you.
也许我错过了它,但有人试过一个简单的通用扩展方法。这对我很有用。您可以通过这种方式避免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;
}
}
#13
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:
int Question = (int)QuestionType.Role
Otherwise, the type is still QuestionType
.
否则,类型仍为QuestionType。
This level of strictness is the C# way.
这种严格程度是C#方式。
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.
或者,您可能会对Visual Basic感到更舒服,因为Visual Basic可以满足许多领域的这种期望。
#14
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 simplify getting int value of current enum value:
这简化了获取当前枚举值的int值:
Question question = Question.Role;
int value = question.getNumberValue();
or
int value = Question.Role.getNumberValue();
#15
int number = Question.Role.GetHashCode();
number
should have the value 2
.
number应该具有值2。
#16
How about a 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();
#17
My fav hack with int or smaller enums:
我最喜欢使用int或更小的枚举:
GetHashCode();
For a 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: Doesn't work for enums based on long
免责声明:不适用于基于long的枚举
#18
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);
}
#19
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;
}
#20
The example I would like to suggest 'to get 'int' value from enum is,'
我想建议'从enum获得'int'值的例子是,'
public enum Sample
{Book =1, Pen=2, Pencil =3}
int answer = (int)Sample.Book;
now the answer will be 1.
现在的答案是1。
I hope this might help someone.
我希望这可能对某人有所帮助。
#21
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;
#22
The easiest solution I can think of is overloading the Get(int)
method like this:
我能想到的最简单的解决方案是重载Get(int)方法,如下所示:
[modifiers] Questions Get(Question q)
{
return Get((int)q);
}
where [modifiers]
can generally be same as for 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:
其中[modifiers]通常可以与Get(int)方法相同。如果您无法编辑Questions类或由于某种原因不想编辑,您可以通过编写扩展来重载该方法:
public static class Extensions
{
public static Questions Get(this Questions qs, Question q)
{
return qs.Get((int)q);
}
}
#23
Try this one instead of convert enum to int:
尝试这个而不是将枚举转换为int:
public static class ReturnType
{
public static readonly int Success = 1;
public static readonly int Duplicate = 2;
public static readonly int Error = -1;
}
#24
In Vb. It should be
在Vb。它应该是
Public Enum Question
Role = 2
ProjectFunding = 3
TotalEmployee = 4
NumberOfServers = 5
TopBusinessConcern = 6
End Enum
Private value As Integer = CInt(Question.Role)
#25
Try this :
试试这个 :
int value = YourEnum.ToString("D");