C# sizeof(enum) alternative? (to workaround resharper false error)?

孤街醉人 提交于 2019-12-04 06:41:08
max

Looks ugly, but may work:

int myEnumSize = Marshal.SizeOf(Enum.GetUnderlyingType(typeof(MyEnum)));


Edit by John Gietzen:
Proof:
enum Enum1 : sbyte { A, B, C, D }
enum Enum2 : short { A, B, C, D }
enum Enum3 : int { A, B, C, D }
enum Enum4 : long { A, B, C, D }

enum Enum5 : byte { A, B, C, D }
enum Enum6 : ushort { A, B, C, D }
enum Enum7 : uint { A, B, C, D }
enum Enum8 : ulong { A, B, C, D }

sizeof(Enum1): 1
sizeof(Enum2): 2
sizeof(Enum3): 4
sizeof(Enum4): 8
sizeof(Enum5): 1
sizeof(Enum6): 2
sizeof(Enum7): 4
sizeof(Enum8): 8

Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum1))): 1
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum2))): 2
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum3))): 4
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum4))): 8
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum5))): 1
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum6))): 2
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum7))): 4
Marshal.SizeOf(Enum.GetUnderlyingType(typeof(Enum8))): 8

The correct solution would be to add a comment before this line stating that the warning generated by the tool is incorrect. This will prevent future maintainers from becoming confused and trying to fix something that's not broken.

I imagine (if you really, really want to) you could use a switch/case on the enumeration. But my guess is the sizeof is there for a reason.

If you're interested in getting the size of the underlying data object of the enum, perhaps a better way would be to get hold of the System.Type object first.

Type type = typeof (MyEnum);
int enumSize = sizeof (Enum.GetUnderlyingType (type));

You can ignore it in ReSharper but it's a bit of a pain and compromises/changes your design. You can put the Enum definition and a method to get the size (using sizeof) in a class in it's own file and click on ReSharper > Options... > Code Inspection > Settings > Edit Items to Skip and then select that file (I'm using R# 5.1).

Obviously you won't get code analysis but you still get the code format cleaning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!