gpt4 book ai didi

c# - 如何使用属性调用类的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:36 25 4
gpt4 key购买 nike

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

有没有办法调用那个方法?

PS/项目是用vbnet写的,不过我觉得c#的解决方法是一样的。

最佳答案

如果您可以找到属性,我猜您拥有该方法的MethodInfo。只需调用 MethodInfo.Invoke 方法,您必须指定要使用的对象的实例(如果是静态方法,则为 null )和所有要传递的参数方法(与原型(prototype)的顺序相同)。

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

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 });

关于c# - 如何使用属性调用类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com