C# 无法将类型“System.Enum”转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1643571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert type 'System.Enum' to int
提问by Benjol
(OK, I'll expose the depths of my ignorance here, please be gentle)
(好吧,我会在这里暴露我的无知深处,请温柔)
Background
背景
I've got a method which looks (a bit) like this:
我有一个看起来(有点)像这样的方法:
public void AddLink(Enum enumVal)
{
string identifier = m_EnumInterpreter(enumVal);
AddLink(identifier);
}
The EnumInterpreter is a Func<Enum, string> that is passed in when the parent class is created.
EnumInterpreter 是在创建父类时传入的 Func<Enum, string>。
I'm using Enum because at this level it is 'none of my business'- I don't care which specific enum it is. The calling code just uses a (generated) enum to avoid magic strings.
我使用 Enum 是因为在这个级别它“不关我的事”——我不在乎它是哪个特定的枚举。调用代码仅使用(生成的)枚举来避免魔术字符串。
Question
题
If the EnumInterpreter sends back an empty string, I'd like to throw an exception with the actual value of enumVal. I thought I would just be able to cast to int, but it the compiler won't have it. What am I doing wrong? (Please don't say 'everything').
如果 EnumInterpreter 发回一个空字符串,我想用 enumVal 的实际值抛出一个异常。我以为我只能转换为 int,但编译器不会拥有它。我究竟做错了什么?(请不要说“一切”)。
回答by Maximilian Mayerl
No, you aren't able to cast it to an int because System.Enum is not an enum, it's just the base class for enums.
不,您无法将其转换为 int,因为 System.Enum 不是枚举,它只是枚举的基类。
EDIT:
编辑:
You can get the value as follows, but it is ugly:
您可以按如下方式获取值,但它很丑陋:
int intVar = (int)enuYourEnum.GetType().GetField("value__").GetValue(objYourEnum);
回答by Ryan Brunner
System.Enum cannot be directly cast to Integer, but it does explicitly implement IConvertible, meaning you can use the following:
System.Enum 不能直接转换为 Integer,但它确实明确实现了 IConvertible,这意味着您可以使用以下内容:
public void AddLink(Enum enumVal)
{
string identifier = m_EnumInterpreter(Convert.ToInt32(enumVal));
AddLink(identifier);
}
Keep in mind that if your Enum is actually using something other than an Integer (such as a float), you'll lose the non-integer data on conversion. Or obviously replace the Convert call with whatever you are converting from (if it's known)
请记住,如果您的 Enum 实际上使用的不是整数(例如浮点数),您将在转换时丢失非整数数据。或者显然用您要转换的任何内容替换 Convert 调用(如果已知)
回答by Hefaistos68
Various things here:
这里有各种各样的东西:
1) the answer of Ryan looks ok, but... I would rather pass the Enum down to the enum interpreter, so that you can do the whole Convert.To... there. If you know that you are using ONLY integer based enums, the Convert.ToInt32() is just fine. Otherwise you may want to add by using either reflection or try/catch other conversions.
1)Ryan 的答案看起来不错,但是...我宁愿将 Enum 传递给 enum 解释器,以便您可以在那里完成整个 Convert.To...。如果您知道您只使用基于整数的枚举,那么 Convert.ToInt32() 就好了。否则,您可能希望通过使用反射或 try/catch 其他转换来添加。
2) You may also consider using members of the Enum class, like .GetName(), .GetValue(), etc. since they deal directly with the defined names and values independent of the enum type.
2) 您也可以考虑使用 Enum 类的成员,如 .GetName()、.GetValue() 等,因为它们直接处理独立于枚举类型的定义的名称和值。
3) technically I would not throw the exception outside the enum interpreter. If that condition is generally true, throw the exception from inside the enum interpreter, so that all uses of the class will benefit of the validation. Or you might end up duplicating code.
3)从技术上讲,我不会在枚举解释器之外抛出异常。如果该条件通常为真,则从枚举解释器内部抛出异常,以便该类的所有使用都将受益于验证。或者你最终可能会复制代码。
4) you seem to have an C++/MFC background judging from your variable naming. You might want to get into C# style naming conventions, it will ease your life when using/reading other peoples code and libraries. Check out MS's StyleCop for a good addin to help with naming.
4) 从您的变量命名来看,您似乎具有 C++/MFC 背景。您可能想要了解 C# 风格的命名约定,它会在使用/阅读其他人的代码和库时减轻您的生活。查看 MS 的 StyleCop 以获取有助于命名的良好插件。
回答by Benjol
I don't know whether to include this in my question, or as an answer. The problem is that it isn't THE answer, but it is the answer that works for me.
我不知道是否将此包含在我的问题中,或作为答案。问题是这不是答案,而是对我有用的答案。
What I discovered, by chance while trying something else, is that if I just wodge it onto the end of a string, I get what I want:
我在尝试其他东西时偶然发现,如果我只是将它放在字符串的末尾,我会得到我想要的:
throw new Exception("EnumInterpreter returns empty string for enumVal=" + enumVal);
//EnumInterpreter returns empty string for enumVal=3720116125
I actually simplified to int in my question, the real data type is uint (in this particular instance). Fortunately, given that I only actually wanted the string, I don't have to worry about that.
我实际上在我的问题中简化为 int ,真正的数据类型是 uint (在这个特定的例子中)。幸运的是,鉴于我实际上只想要字符串,我不必担心。
I'm not sure which of the three other answers is 'right', so vote away...
我不确定其他三个答案中的哪一个是“正确的”,所以请投票...
回答by mike
Why not parse the enum to a string and return the actual enum value?
为什么不将枚举解析为字符串并返回实际的枚举值?
public enum MyEnum { Flower = 1, Tree = 2, Animal = 3 };
string name = MyEnum.Flower.ToString(); // returns "Flower"
I think .ToString()
is deprecated and I'm not sure about the new way to do it. I would've thought the actual enum representation would be more useful than the int?
我认为.ToString()
已弃用,我不确定这样做的新方法。我原以为实际的枚举表示会比 int 更有用?
回答by Joo Park
try this..
尝试这个..
m_EnumInterpreter((int) (object) enumVal);
m_EnumInterpreter((int) (object) enumVal);
回答by Rhys van der Waerden
I understand that this is probably not the solution to your exact problem, but I just want to post how I solved this for a particular API I was using.
我知道这可能不是您确切问题的解决方案,但我只想发布我如何为我使用的特定 API 解决这个问题。
int result = (int) (ActualEnumType) MethodThatReturnsSystemEnumType( arg1, arg2 );
Hopefully that will be of help to someone. Double cast FTW.
希望这会对某人有所帮助。双投 FTW。