public Thing MyMethod
{
Cat cat = new Cat();
Dog dog = new Dog();
return new Thing();
}
How would I get the list of classes that this method body uses? Ie...
Cat, Dog, and Thing.
Koush
On 1/13/10, Koush <kou...@gmail.com> wrote:
> public Thing MyMethod
> {
> Cat cat = new Cat();
> Dog dog = new Dog();
> return new Thing();
> }
>
> How would I get the list of classes that this method body uses? Ie...
> Cat, Dog, and Thing.
Just iterate over the instructions in the body of MyMethod. Switch on
the opcode of the instruction, if its OperandType is InlineType, the
operand of the Instruction will be a TypeReference.
A InlineToken operand may also be a TypeReference (but it can be a
FieldReference or a MethodReference as well).
--
Jb Evain <j...@nurv.fr>
|
public static List<MethodCalled> getMethodsCalledInsideAssembly(String assemblyToLoad) |
|
{ |
|
try |
|
{ |
|
var methodsCalled = new List<MethodCalled>(); |
|
foreach (MethodDefinition methodDefinition in getMethods(assemblyToLoad)) |
|
methodsCalled.AddRange(getMethodsCalledInsideMethod(methodDefinition)); |
|
return methodsCalled; |
|
} |
|
catch (Exception ex) |
|
{ |
|
DI.log.ex(ex, "in CecilUtils.getMethodsCalledInsideAssembly"); |
|
return null; |
|
} |
|
} |
|
|
|
public static List<MethodCalled> getMethodsCalledInsideMethod(MethodDefinition methodDefinition) |
|
{ |
|
try |
|
{ |
|
var methodsCalled = new List<MethodCalled>(); |
|
if (methodDefinition.Body != null) |
|
{ |
|
SequencePoint currentSequencePoint = null; |
|
foreach (Instruction instruction in methodDefinition.Body.Instructions) |
|
{ |
|
currentSequencePoint = instruction.SequencePoint ?? currentSequencePoint; |
|
if (instruction.Operand != null) |
|
{ |
|
switch (instruction.Operand.GetType().Name) |
|
{ |
|
case "MethodReference": |
|
case "MethodDefinition": |
|
methodsCalled.Add(new MethodCalled((IMemberReference)instruction.Operand, currentSequencePoint)); |
|
break; |
|
default: |
|
break; |
|
} |
|
} |
|
} |
|
} |
|
return methodsCalled; |
|
} |
|
catch (Exception ex) |
|
{ |
|
DI.log.ex(ex, "in CecilUtils.getMethodsCalledInsideMethod"); |
|
return null; |
|
} |
| } |
|
public class MethodCalled |
|
{ |
|
public IMemberReference memberReference { get; set;} |
|
public SequencePoint sequencePoint { get; set; } |
|
|
|
public MethodCalled(IMemberReference _memberReference, SequencePoint _sequencePoint) |
|
{ |
|
memberReference = _memberReference; |
|
sequencePoint = _sequencePoint; |
|
} |
| } |
--
--
mono-cecil