Is it possible to have two functions with the same signature called in different contexts? (Attribute Manipulation)

I ran into an interesting problem, perhaps as a result of developing a third party API I have no control over.

Consider the following code example:

class MyClass : ThirdPartyClass {
    void SpecialFunction() {
        //...
    }
}

      

Third party API calls SpecialFunction

after internal processing.

I can add an attribute to tell the API that it should be called before internal processing:

[DoFirst]
void SpecialFunction() { ... }

      

However, this means that I must have two additional classes if I want to run the same function before and after the internal processing of the API:

class MyClass : ThirdPartyClass {
    public void DoSpecialFunction() { ... }
}

class MyClassPre : ThirdPartyClass {
    MyClass myClass;
    [DoFirst]
    void SpecialFunction() {
        myClass.DoSpecialFunction();
    }
}

class MyClassPost : ThirdPartyClass {
    MyClass myClass;
    void SpecialFunction() {
        myClass.DoSpecialFunction();
    }
}

      

This is obviously not valid:

class MyClass : ThirdPartyClass {
    [DoFirst]
    void SpecialFunction() { _SpecialFunction(); }

    void SpecialFunction() { _SpecialFunction(); }

    void _SpecialFunction() { ... }
}

      

Is it possible that some C # can manipulate attributes or function signatures so that no additional classes are required?

Perhaps through some extension method? ( SpecialFunction

not an override)

+3


source to share


1 answer


As mentioned in the comments, you cannot have two methods with the same name and arguments that differ only in their decorated attributes.

Presumably the third party API uses reflection to identify SpecialFunction()

, and so you should be able to simplify your workaround like this:

// An instance of this class will Do After
public class MyClass : ThirdPartyClass 
{
    public virtual void SpecialFunction() 
    { 
       // All the work goes here
    }
}

// An instance of this class will Do First
public class MyClassPre : MyClass 
{
    [DoFirst]
    public override void SpecialFunction() 
    {
        base.SpecialFunction();
    }
}

      



If a third-party API is provided to you by an organization you partner with or from whom you use services, you can ask to add an attribute [DoAfter]

that also triggers the default behavior. In this case, you can simply decorate like this:

class MyClass : ThirdPartyClass 
{
    [DoFirst]
    [DoAfter]
    void SpecialFunction()
    {
        //  ...
    }
}

      

+4


source







All Articles