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

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

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

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

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

获得方法列表后,您将使用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. } 

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