Is there a way to apply the attribute to the method that gets executed first?

Without using a library like PostSharp, is there a way to set up a custom attribute that can have logic in the event that it is bound to a method, will PRIOR execute that method?

+3


source to share


1 answer


Not; Attributes are not intended for code entry. Tools like postsharp make do with smoke and mirrors, but without it: no. Another option could be a decorator pattern, perhaps dynamically implementing the interface (not trivially in any way). However, adding a method-method-method to the beginning of the method (s) is much easier and presumably great, because if you have access to add attributes, you have access to add the method-call.

Or put another way: tools like postsharp exist as they don't exist out of the box.

// poor man aspect oriented programming
public void Foo() {
    SomeUtility.DoSomething();
    // real code
}

      



In some cases, subclasses can be useful, especially if the subclass is executed at runtime (metaprogramming):

class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
    public override void Foo() {
        SomeUtility.DoSomething();
        base.Foo();
    }
}

      

+5


source







All Articles