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

发布于 2024-09-01 03:30:38 字数 103 浏览 11 评论 0原文

我有一堂有很多方法的课程。

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

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

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

I have a class with a bunch of methods.

some of these methods are marked by a custom attribute.

I would like to call all these methods at once.

How would I go about using reflection to find a list of all the methods in that class that contains this attribute?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里梦着梦中梦 2024-09-08 03:30:38

获取方法列表后,您可以使用 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.

}

Once you get the list of methods, you would cycle query for the custom attributes using the GetCustomAttributes method. You may need to change the BindingFlags to suit your situation.

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.

}
世界和平 2024-09-08 03:30:38

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

First, you would call typeof(MyClass).GetMethods() to get an array of all the methods defined on that type, then you loop through each of the methods it returns and call methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), true) to get an array of custom attributes of the specified type. If the array is zero-length then your attribute is not on the method. If it's non-zero, then your attribute is on that method and you can use MethodInfo.Invoke() to call it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文