Say you have two simple interfaces and their methods:
ISerializable.Serialize(IValueWriter writer)
IValueWriter.WriteInt32(Int32 value)
IValueWRiter.WriteInt64(Int64 value)
When a class implements ISerializable
I would like to be able to know which calls are made to the IValueWriter
inside the ISerializable.Serialize(IValueWriter writer)
implementation and generate a call graph from that. All of this needs to be done at run-time using reflect开发者_如何学Pythonion and without calling the Serialize method and it will be done also on classes which I have no control over as far as the code inside them goes.
Example:
public sealed class SomeObject : ISerializable
{
private readonly Int32 first;
private readonly Int64 second;
public SomeObject(Int32 first, Int64 second)
{
this.first = first;
this.second = second;
}
public void Serialize(IValueWriter writer)
{
writer.WriteInt32(this.first);
writer.WriteInt64(this.second);
}
}
The call graph would be:
SomeObject -> Serialize | -> IValueWriter.WriteInt32
| -> IValueWriter.WriteInt64
How would one accomplish this in a nice and clean fashion?
What I am truly aiming for is basically a MethodInfo[]
of the calls made in a specific implementation of an interface method.
Yes, you can do this using reflection. I wouldn't really call it "runtime" when none of the code being analyzed is running.
- Iterate all types in the assembly.
- Filter for types implementing
ISerializable
- Find the method implementing
ISerializable.Serialize
- Fetch the IL
- Look for
callvirt
instructions where the method token matches a method withinIValueWriter
.
There's an open source project, ILSpy, which should be a good example of how to decode IL instructions and look for method calls.
cleanest way is AOP. take a look to PostSharp
All you need to do is to create some Attributes and add them to your methods, to be logged, etc.
as far as I know they manipulate the IL after compilation.
精彩评论