the*_*row 5 .net c# enumeration
我有一个接受Enum(基类)作为参数的函数:
public void SomeFunction(Enum e);
Run Code Online (Sandbox Code Playgroud)
但是由于某种原因我无法将其转换为int.我可以得到枚举值的名称,但不是它的整数表示.
我真的不关心枚举的类型,我只需要积分值.我应该通过int吗?或者我在这里做错了什么?
the*_*oop 13
int i = Convert.ToInt32(e);
Run Code Online (Sandbox Code Playgroud)
无论枚举的底层存储如何,这都将起作用,而其他解决方案将抛出一个InvalidCastException如果枚举存储在除int32(例如,a byte或short)以外的任何内容中
Enum实际上并不是一个令人困惑的... 它是枚举的盒装副本; 仍然,以下应该工作:
int i = (int)(object)e;
Run Code Online (Sandbox Code Playgroud)
(此(object)演员表不会添加一个框,因为它已经装箱)
另请注意,并非所有枚举都基于int; 对于非int枚举,这种拆箱技巧可能会失败.
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |