vendredi 7 octobre 2022

C# Getting methods with attribute in abstract class

I'm trying to get methods from which have a specific Callback attribute inside the constructor of an abstract class. The challenge here is that I also want the methods from the concrete class which have this attribute.

My abstract class:

public abstract class BaseScript
{
    protected readonly CallbacksDictionary Callbacks;

    protected BaseScript(CallbacksDictionary callbacks)
    {
        // Get all methods with the [Callback] attribute including the concrete instance
        var methodsWithCallbackAttr = // ?
    }
}
public class SomeScript : BaseScript {
    public SomeScript(CallbacksDictionary callbacks) : base(callbacks) { }

    [Callback("transaction")]
    internal Task<bool> Transaction(int amount) {
       // I need to get this method
    }

    internal Task<bool> GetBalance(int accountId) {
         // But not this method
    }
}

In the example above I want methodsWithCallbackAttr to be a list containing the Transaction method if the concrete instance is SomeScript i.e. I don't want all the methods from all the classes that inherit from BaseScript and have the Callback attribute.

I've tried the following. Which does not work. This only returns the methods from BaseScript which have the Callback attribute, but not the methods from SomeScript.

var callbackMethods = GetType().GetMethods()
    .Where(m => m.GetCustomAttributes(typeof(CallbackAttribute), true).Length > 0);




Aucun commentaire:

Enregistrer un commentaire