Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have a look at an Aspect Oriented Programming (AOP) Framework such as <a href="http://www.sharpcrafters.com/" rel="nofollow">PostSharp</a>. PostSharp allows you to create attributes which you can use to decorate classes, methods...etc.</p> <p>Such an attribute (or aspect) can be programmed to inject code before your method executes and after its finished.</p> <p>For example, logging using attributes:</p> <p><a href="http://www.sharpcrafters.com/solutions/logging" rel="nofollow">http://www.sharpcrafters.com/solutions/logging</a></p> <p>To be complete I'll include a small example. Let's say we want to log a message each time a method executes. You can create an aspect (PostSharp attribute) for this purpose.</p> <pre><code>[Serializable] public class LogAttribute : OnMethodBoundaryAspect { public override void OnExit(MethodExecutionArgs args) { base.OnExit(args); Console.WriteLine(String.Format("{0}.{1}: {2}", args.Method.DeclaringType.Name, args.Method.Name, args.ReturnValue)); } } </code></pre> <p>Here the aspect writes out a message to the console window when the method is finished.</p> <p>Now you can apply this attribute to a method.</p> <pre><code>public class Calculator { [Log] public int Add(int x, int y) { return x + y; } } </code></pre> <p>Voila, this makes your method more readable as it is not being cluttered by logging code which adds nothing to the actual functionality of the method (adding two numbers). This results in more readable and maintainable code.</p> <p>A while back I wrote an article about it on my blog. It's quite lenghty to copy here, but it demonstrates how to build such attributes and to replace common code such as logging, exception handling...etc. by attributes so that you don't clutter all of your method with this kind of code:</p> <p><a href="http://cgeers.com/2011/05/08/postsharp/" rel="nofollow">http://cgeers.com/2011/05/08/postsharp/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload