I have introduced XC # In a previous article. With XC #, you can easily insert pre-and post-condition checks on a method. The implementation of XC # Is to dynamically Add the corresponding code to the original code based on the specified attribute inserted during compilation.
Lostinet contextboundmodel (CBM) is an AOP. net Framework, based on CBM, can easily implement pre-and post-condition checks similar to XC #, and has greater flexibility, because we can customize various inspection conditions.
The following example shows how to apply the prefix and Postfix conditions to the setage () method and getage () method of the person class:
Public class person: aspectobject
{
...
Public void setage ([Agearg]Int32 age)
{
_ Iage = age;
}
[Ageresult]
Public int32 getage ()
{
Return _ iage;
}
The preceding setage () method needs to check whether the input parameter age is required for age requirements (for example, age greater than 16, age less than 150), while getage () method, you need to check whether the returned value is required. The two attributes added to parameters and methods, agearg and ageresult both implement the attribute of the lostinet. contextboundmodel. imessagehandlerattribute interface, so they can be used to mark interception.
The following demonstrates the implementation of ageresultattribute:
[Attributeusage (attributetargets. Method)]
Public class ageresultattribute: attribute, imessagehandler, imessagehandlerattribute
{
...
Public imethodreturnmessage processmessage (imethodcallmessage mcm, aspectobjectproxy proxy, messagehandlerqueue Queue)
{
Imethodreturnmessage result = queue. invokenext (MCM, proxy );
If (convert. toint32 (result. returnvalue) <0)
{
Throw new applicationexception ("the returned value cannot be" + result. returnvalue. tostring ());
}
Return result;
}
}
In the processmessage () method, the code first calls the "real" method code and then checks the return value.
If you are interested, click here to download the source code of this demo project. Download the latest contextboundmodel version.
[All references to contextboundmodel in this article are allowed by lostinet]