如何使用反射来调用具有特定自定义属性的所有方法?

Dis*_*ive 6 c# reflection attributes methodinfo

我有一个有很多方法的课.

其中一些方法由自定义属性标记.

我想立即调用所有这些方法.

我如何使用反射来查找该类中包含此属性的所有方法的列表?

Tho*_*mas 7

获得方法列表后,您将使用GetCustomAttributes方法循环查询自定义属性.您可能需要更改BindingFlags以适合您的情况.

var methods = typeof( MyClass ).GetMethods( BindingFlags.Public );

foreach(var method in methods)
{
    var attributes = method.GetCustomAttributes( typeof( MyAttribute ), true );
    if (attributes != null && attributes.Length > 0)
        //method has attribute.

}
Run Code Online (Sandbox Code Playgroud)


Dea*_*ing 6

首先,您将调用typeof(MyClass).GetMethods()来获取该类型上定义的所有方法的数组,然后循环遍历它返回的每个方法并调用methodInfo.GetCustomAttributes(typeof(MyCustomAttribute),true)到获取指定类型的自定义属性数组.如果数组为零长度,那么您的属性不在方法上.如果它不为零,那么您的属性就在该方法上,您可以使用MethodInfo.Invoke()来调用它.