If you're not aware of some of OOP's flaws in actual development, don't look down!
If you don't understand AOP, or AOP-like ideas, take a look at AOP-related understanding.
If you are a concept party, or experience party, or the herd party, please do not read it!
I realize is only a small function, is not AOP I do not know, and not the main, the title that write just let people see what this article is about, and I can not think of what to write a title.
Because I saw other people talk about AOP, pull a lot of things, agents, emit and so on, but one did not read (I hate complex)!
But one thing that is useful to me is several types of notification:
1, before the target method call (before)
2, after the target method call (after)---Target method exception also executes
3, the target method returned (after return)---The target method exception does not execute
3, before and after the target method call (around)
4, when the target method throws an exception (throw)
I feel a little bit more understanding, so the implementation below is based on these 6 types:
1, before the target method call (before)
2, after the target method call (after)--the target method exception is not executed!
3, after the target method call (Afterensure)--the target method exception is also executed.
4, before and after the target method call (Around)--the target method exception, after is not executed
5, before and after the target method call (aroundensure)--target method exception, after also executed
6, when the target method throws an exception (Throw)
Given the variety of notification processing, a unified interface (generic interface) is needed, and here the abstract analogy. NET interface is more appropriate: (This component has only two classes, which is one of them)
Public abstract class Aspectadvice
{public
virtual void before (object target, MethodInfo mi, params object[] args {} public
virtual void after (object target, MethodInfo mi, params object[] args) {} public
virtual void Throw ( Object target, MethodInfo mi, params object[] args) {}
}
Three method is enough, the three methods and the target method of different calling logic can meet the above 6 kinds of notifications, the following analysis.
For the sake of description, I also take logging as an example, the following is the target class, and the log class (can you call it slices?) Oh
public class MyClass
{
//No return value public
void Act ()
{
Console.WriteLine ("Myclass.act ()");
}
There is a return value of public
int Fun (string str)
{returns
str. Length;
}
private int m_num=10;
With the object member M_num, an exception public
int Divide (int n)
{return
m_num/n
}
can occur. static method public
static void Sfun (String str)
{
Console.WriteLine (str);
}