Question

Im parsing through a type with Mono.Cecil. How can i check if the type im parsing is accessing getter Methods of other classes?

For accessing the fields directly I have found a solution:

foreach (MethodDefinition method in type.Methods)
            {
                foreach (Instruction instruction in method.Body.Instructions)
                {

                    if (instruction.OpCode == OpCodes.Ldfld)
                    {
                        FieldReference field = instruction.Operand as FieldReference;



                        if (fields.Contains(field.ToString()) && !accesses.Contains(field.ToString()))
                        {
                            accesses.Add(field.ToString());
                            Console.WriteLine("Class " + type.Name + " accesses field " + field.Name + " of a foreign class.");
                        }

                    }
                }
            }

But how can I solve the problem if the field of another class is accessed by a getter method?

Or to simplify the question: how can i determine if a method is a getter method using CIL instructions? and how can i detect which field is returned?

Was it helpful?

Solution

As Donnie suggests in the comments, getters and setters are just like any other methods. They can return pretty much whatever they want, be as complex as they want, etc. So whatever you will do will be at best, an educated guess.

To begin with, you can have a look at the semantic attributes of the MethodDefinition. If it says that the method is a getter or a setter, at least you'll know if it's attached to a property.

Now, you can also analyse the IL to try to find a certain pattern, like I did in my blog post about retrieving the backing field of a property. You'd have to adjust the code to use Mono.Cecil instead of Mono.Reflection, but it shouldn't be a big deal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top