简体   繁体   中英

How do I find out if an enum value is used at Runtime?

We are using a quasi dynamic method to create enums from sql lookup tables using t4 templates. The template generates an enum for every table that conforms to the lookup patter. Several of these enums are not being used in code, but any could be.

This has been fine and dandy, but now we have been asked to create a lookup management interface so that users can add new values, edit descriptions, etc.

They don't want to modify any items that are currently being used in code as an enum value, so is there a simple (or not so simple) way to query our assemblies to find out if an enum value is used?

We have a lot of code similar to this made-up example:

public Role GetAdminRole
{
  using (myContext ctx = new myContext()
  {
    return ctx.Roles.Where(i=> i.RoleId == (int)RoleEnum.Admin).SingleOrDefault();;
  }
}

Is there a way to use the Type.FindMembers() and build a filter that can query the internals of a method?

I've looked at the System.Reflection.Emit namespace, which seemed promising based on the EnumBuilder class, but couldn't figure out how to hook up a builder to an existing assembly. The System.Diagnostics.CodeAnalysis namespace sounds interesting, but it only contains two attributes (for suppressing warnings and excluding code from coverage).

EDIT: While poking through ILSpy I discovered that I knew, but didn't put together, that enum values in methods get converted to their integer value when used in the above manner when compiled.

If you insist on checking at runtime you could use the GetILAsByteArray method on the MethodBody class to get the IL and parse that , searching for places where your enumerations are used.

As you can imagine, this is going to be very painful, as you have to go through all of the methods in all of the types in all of the modules, in all of the assemblies.

I strongly recommend that you use some sort of static analysis on the code ; ReSharper , for example, can tell you whether or not members are used.

If you want to code an in-house solution, you can take a look at Roslyn to analyse your code (warning, it's a CTP as of this writing); you can parse the code in your project and do the analysis yourself.

That said, you're best off finding a tool that's going to an analysis of the code and not of the final, output assembly.

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