Search code examples
c#metadatabindingflags

BindingFlags for methods with Attributes


Is it possible to use the BindingFlags for methods that have attributes? I did look over msdn at BindingFlags and nothing showed up. This is how one of my methods looks like :

[TestMethod()
,TestCategory("ActionCol")
,TestCategory("DataDriven")
,DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", @"|DataDirectory|\ActionCol\actionCol.csv", "actionCol#csv", DataAccessMethod.Sequential)
,DeploymentItem(@"..\ActionCol\actionCol.csv")]
public void ActionCol_Insert_LeftGrid(){}

I am using reflection to add to a listbox all my void methods, but I want exclusively to add just the methods with this attribute..

This is how I am using BindingFlags:

methArr = e.myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Where methArr is an MethodInfo-instance


Solution

  • Binding flags are not used in this case.

    Instead what you must do is enumerate the methods for a given type and evaluate whether a method is decorated with a particular attribute.

    The following code will find all of the methods of myType who are decorated with the TestMethod attribute using Linq:

    var methArr =
        e.myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            .Where(method => method.GetCustomAttributes(typeof (TestMethodAttribute), false).Any());