C # attribute to change methods

all. Maybe I did not know enough about Google, but I can not find a single example on this issue.

In C #, is it possible to create a custom attribute that applies to a class that modifies all its methods? For example, adds Console.WriteLine("Hello, i'm modified method");as the first line (or is it the equivalent of IL if it is executed at run time)?

+2
source share
2 answers

Yes, you can do it, but no, it is not built into C #. According to Eric, this method is known as aspect-oriented programming.

PostSharp , . IL-weaving, .

, , :

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method | MulticastTargets.Class,
                         AllowMultiple = true,
                         TargetMemberAttributes = MulticastAttributes.Public | 
                                                  MulticastAttributes.NonAbstract | 
                                                  MulticastAttributes.Managed)]
class MyAspect : OnMethodInvocationAspect
{
    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        Console.WriteLine("Hello, i'm modified method");

        base.OnInvocation(eventArgs);
    }
}

MyAspect , . , , TargetmemberAttributes MulticastAttributeUsage. , .

( AOP ).

+5

. - (AOP).

AOP pointcut, , , , . . , /weaver/ / .

+5

Source: https://habr.com/ru/post/1769711/


All Articles