Question

I'm attempting to make an instruction editor in C# and I'm stuck on creating instructions. I need to be able to convert a string to an OpCode with Mono.Cecil but it doesn't seem to be able to do that. If it's any easier I could create a Dictionary<string, OpCode> and populate that by enumerating through the OpCodes in OpCodes, however OpCodes is only class that contains the OpCodes as variables instead of in a list (I think this might be for .NET 1 support) preventing me from enumerating through them. That's where I arrive to the problem, how can I either convert a string to an OpCode, or enumerate through every OpCode (whichever is easier/faster).

Was it helpful?

Solution

Reflection would help you here if performance is not a problem.

Here's how you go.

var opCodes = typeof(OpCodes)
                    .GetFields(BindingFlags.Static | BindingFlags.Public)
                    .Where(x=> x.FieldType == typeof(OpCode))
                    .Select(x=> (OpCode)x.GetValue(null))
                    .ToArray();

foreach(var opcode in opCodes)
{
   //Do whatever with opcode
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top