代码之家  ›  专栏  ›  技术社区  ›  Diskdrive

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

  •  6
  • Diskdrive  · 技术社区  · 16 年前

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

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

    2 回复  |  直到 16 年前
        1
  •  7
  •   Thomas    16 年前

    一旦得到方法列表,就可以使用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.
    
    }
    
        2
  •  6
  •   Dean Harding    16 年前

    typeof(MyClass).GetMethods() 要获取在该类型上定义的所有方法的数组,您需要遍历它返回和调用的每个方法 methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), true) 获取指定类型的自定义属性数组。如果数组长度为零,则属性不在方法上。如果它是非零的,那么您的属性在该方法上,您可以使用 MethodInfo.Invoke()