gpt4 book ai didi

c# - 在作为参数传递的对象上调用作为参数传递的方法

转载 作者:行者123 更新时间:2023-11-30 21:54:58 24 4
gpt4 key购买 nike

我有一个类定义了几个具有相同签名的函数

public class MyClass
{
public string MyParam1() ...
public string MyParam2() ...
...
}

我想从另一个类调用作为参数传递的对象的方法

void MyFunction(MyClass anObject, Func<string> aMethod)
{
string val = ??? // Here call aMethod on anObject
}

我很确定可以使用反射来做到这一点,但是有没有一种不太困难的方法来做到这一点?

事实上我有一组对象,而不是单个对象,这就是为什么我不能直接调用对象的方法。

最佳答案

如果您将实例方法作为函数传递,它已经绑定(bind)到实例,因此您的anObject 在这种情况下是无用的。

此代码已在this 上运行:

MyFunction(null, this.DoSomething);

此处 val 将始终是调用者上下文中 this.DoSomething 的结果:

string val = aMethod();

您可以做的不是传递实例方法,而是创建一个具有 anObject 参数的静态方法。这样,您的静态方法就可以执行特定于实例的任务。

public string MyParam2(MyClass instance) { }

void MyFunction(MyClass anObject, Func<MyClass, string> aMethod)
{
string val = aMethod(anObject);
}

关于c# - 在作为参数传递的对象上调用作为参数传递的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32718294/

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