简体   繁体   中英

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 ie 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);

As @Dai mentioned in their comment. I needed to specify some additional binding flags because the methods I was looking for are internal and instance specific. The code now looks as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM