简体   繁体   中英

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

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

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