[英]Enum as parameter: Get name and index
I have an enum like this: 我有一个这样的枚举:
public enum Global
{
txt_test = 123
}
Now I want to use a call like this: 现在,我想使用这样的呼叫:
var text = lib.Get(Global.txt_test);
Method: 方法:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = ?; // (int)enumeration not working
...
}
How to get the index of an enum in this case? 在这种情况下如何获取枚举的索引? Or am I doing it wrong at all?
还是我做错了?
Thank you. 谢谢。
Solution: 解:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
...
}
Enum are convertible to int
for retrieving their values: 枚举可转换为
int
以获取其值:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
// ...
return null;
}
Note that this will work because your enumeration is type of int by default. 请注意,这将起作用,因为默认情况下您的枚举是int类型。 Enums can still be other value type like long :
枚举仍然可以是其他值类型,例如long:
enum Range : long { Max = 2147483648L, Min = 255L };
In this case, the conversion will lost precision. 在这种情况下,转换将失去精度。
If you only need the enum value (what you are calling "index") as a string, the best way is to use custom format strings as documented here: http://msdn.microsoft.com/en-us/library/c3s1ez6e%28v=vs.110%29.aspx 如果只需要枚举值(称为“索引”)作为字符串,则最佳方法是使用此处记录的自定义格式字符串: http : //msdn.microsoft.com/zh-cn/library/c3s1ez6e %28V = vs.110%29.aspx
For example: 例如:
public TextString Get(Enum enumeration)
{
string index = enumeration.ToString("D");
// ...
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.