开发者

c# Iterate mehods in class to see if a method is being called

The basic question is how can I determine if a certain string is contained in each method of a class?

We have a requirement that all methods in a certain class are making a logging call. I want to iterate through the methods in this class and see if开发者_如何学JAVA each methods is making this call. I know I can use reflection to iterate the methods in a class, but how could I get the code in each method so I can do an IndexOf() ?

Ok, some more info. Only certain methods need to call the logger (determined by me) We want to be able to make sure that all methods either call the logger, have the logger called that is commented out so that we can run a program and determine what new methods have been added that don't have the logger called or commented out logger call. Each month a group will determine if a method merits logging or not. I am just trying to come up with an automated way to show all methods where logging has or has not been addressed.


You may want to look into Post Sharp - http://www.sharpcrafters.com/postsharp - or some other Aspect Oriented Programming framework. This would allow you to attach the logging to the methods once and not have to do it in each method.


You probably don’t want to write all the code from scratch as a standalone program. For similar checks, you should probably write just a custom rule for FxCop/Code Analysis tools. That would be much easier, plus you can use the infrastructure around, like automatic checking on commit etc.


To get all the public instance methods in a class using reflection, just do:

MethodInfo[] minfos = typeof(MyType).GetMethods();
foreach (MethodInfo mi in minfos)
{
   Console.WriteLine("Public instance method: " + mi.Name);
}

if you need to also get the static or private method, you'll need to use the other GetMethods overload, like this:

MethodInfo[] minfos = typeof(ConfigurationItemType).GetMethods(
   BindingFlags.Static | BindingFlags.Instance | 
   BindingFlags.NonPublic | BindingFlags.Public);


EDIT ActiveSharp seems to be doing what you need programmatically. Check the example under "Inspecting MSIL at Runtime (lightweight alternative to FxCop)" on this page

System.Reflection.MethodInfo methodToLookAt = ....; // obtain this via normal reflection, e.g. Type.GetMethod

ActiveSharp.Inspection.MethodInspector ins = new MethodInspector(methodToLookAt, false);

// what are all the methods that it (directly) calls?
IEnumerable<MethodBase> callees = ins.AllCalledMethods;

If you want to do it the hard way and try inspecting the CIL via reflection, you can try reading this article

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜