开发者

Preprocessing C# - Detecting Methods

I require the ability to preprocess a number of C# files as a prebuild step for a project, detect the start of methods, and insert generated code at the start of the method, before any existing code. I am, however, having a problem detecting the opening of a method. I initially tried a regular expression to match, but ended up with far too many false positives.

I would use reflection, but the MethodInfo class does not reference the point in the original source.

EDIT: What I am really trying to do here is to support pre-conditions on methods, that pre-condition code being determined by attributes on the method. My initial thought being that I could look for the beginning of the method, and then insert 开发者_高级运维generated code for handling the pre-conditions.

Is there a better way to do this? I am open to creating a Visual Studio Addin if need be.

This is a .NET 2.0 project.

Cheers


PostSharp or Mono.Cecil will let you do this cleanly by altering the generated code without getting into writing a C# parser which is unlikely to be core business for you...

Havent done anything of consequence with PostSharp but would be guessing its more appropriate than Mono for implementing something like preconditions or AOP. Alternately you might be able to do something AOPy with a DI container like Ninject

But of course the applicability of this idea Depends - you didnt say much other than that you wanted to insert code at the start of methods...

EDIT: In light of your desire to do preconditions... Code Contracts in .net 4 is definitely in that direction.

What sort of a tool do you have? Whats wrong with having a single Mono.Cecil.dll DLL shipped? Either way something other than a parser is the tool for the job.


I am sure there is an easier way but this might be a good excuse to take MGrammer for a spin.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜