简体   繁体   中英

Eazfuscator.NET breaks Enum.IsDefined

In my code I make use of many small enums:

enum UserRequest : byte { Burp=1, Sneeze=2, Fart=3 }

I often need to validate integer input before converting it to this enum.

bool valid_input = Enum.IsDefined(typeof(UserRequest), user_byte_value);

This approach does not work when the enum makes use of the FlagsAttribute; Enum.IsDefined cannot automatically combine flags to make a specified value. However, I've been able to work around not needing FlagsAttribute.

However, TIL that Eazfuscator.NET 's obfuscation breaks Enum.IsDefined. I knew it was a possibility, but I was hoping it wouldn't since it's not in the System.Reflection namespace (reportedly though, it makes heavy use of System.Reflection).

So I'm wondering if anyone knows any good alternatives. I'm specifically after the following:

  1. Allows checking if an integer is in a specified enum.
  2. Compatible with .NET Framework 2.0 and the Mono Framework.
  3. Survives obfuscation without explicitly disabling it (using attributes or some GUI tool).

In the event others run into this same problem, and find this article, the solution I went with was to add an additional enum member to each of my enums.

enum UserRequests : byte
{
    Burp = 0,
    Sneeze = 1,
    Fart = 2,
    /* Maximum Valid Value */
    MAXVAL = Fart
}

This is a practice I remember using in C ((non-ANSI) with #defines) to iterate over enum values, its only downside is that it's hard to maintain.

I wrote a generic function to lesson the burden (header shown below); I still have to explicitly pass the MAXVAL member, but it's less work than I thought. And of course, it survives obfuscation and is portable.

public static bool TryParseByteToEnum<T>(byte input_byte, 
    out T enum_member, T max_value) where 
        T : struct, IConvertible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM