如何使用属性在类上调用方法

本文关键字:调用 方法 何使用 属性 | 更新日期: 2023-09-27 18:35:42

我想在我有引用的类上调用一个方法。我要调用的方法具有自定义属性。目前我可以找到此属性并调用我的类属性的属性。

有没有办法调用该方法?

PS/该项目是用vbnet编写的,但我认为解决方案在c#中是相同的。

如何使用属性在类上调用方法

如果你能找到属性,我想你有该方法的MethodInfo。只需调用 MethodInfo.Invoke 方法,您必须指定要使用的对象的实例(如果是静态方法,则null)以及要传递给该方法的所有参数(按原型的相同顺序)。

例如,如果您必须使用此原型调用方法:

void Foo(string name, int value);

你有一个函数来查找该方法(搜索给定的属性):

MethodInfo FindMethodWithAttribute(Type attributeType, Type objectType);

您可以使用以下代码查找并调用该方法(假设对象anObject):

MethodInfo method = FindMethodWithAttribute(
    typeof(MyAttribute), // Type of the "marker" attribute
    anObject.GetType()); // Type of the object may contain the method
method.Invoke(anObject, new object[] { "someText", 2 });