C# 对作为参数传递的对象调用作为参数传递的方法

C# 对作为参数传递的对象调用作为参数传递的方法,c#,reflection,func,C#,Reflection,Func,我有一个类定义了几个具有相同签名的函数 public class MyClass { public string MyParam1() ... public string MyParam2() ... ... } 从另一个类中,我想对作为参数传递的对象调用作为参数传递的方法 void MyFunction(MyClass anObject, Func<string> aMethod) { string val = ??? // Here call a

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

public class MyClass
{
    public string MyParam1() ...
    public string MyParam2() ...
    ...
}
从另一个类中,我想对作为参数传递的对象调用作为参数传递的方法

void MyFunction(MyClass anObject, Func<string> aMethod)
{
    string val = ??? // Here call aMethod on anObject
}
void MyFunction(MyClass对象,Func方法)
{
字符串val=???//这里调用一个对象上的aMethod
}
我很确定使用反射可以做到这一点,但是有没有一种不难做到的方法呢


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

你不必担心
一个对象,因为
aMethod
已经绑定到一个实例。委托的定义是它是一个代理

因此,以下内容应足够:

void MyFunction(Func<string> aMethod)
{
    string val = aMethod();
}
void MyFunction(Func-method)
{
字符串val=aMethod();
}

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

此代码已在该
上运行:

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);
}
公共字符串MyParam2(MyClass实例){}
void MyFunction(MyClass anObject,Func方法)
{
字符串val=aMethod(一个对象);
}

如果确实要对对象调用给定的方法,则不使用
Func
,而是传入对象和方法的名称:

class Test
{
    public static void SayHello()
    {
        Console.WriteLine("Hello");
    }
}

void Main()
{
    var t = new Test();
    var methodInfo = t.GetType().GetMethod("SayHello");
    methodInfo.Invoke(t, null);

}
执行时,将打印此文件

Hello

由于它将调用
Test
实例
t

上的
SayHello
方法,因此它的可能副本并不完全清楚您在这里要问什么。委托已经知道应该调用哪个实例。您可以这样调用您的
MyFunction
MyFunction(someObject,()=>“test”)
在这种情况下,传递的代理不是来自或在
someObject
上,您希望在这里发生什么?对不起,我试图使问题尽可能简单,但没有指出一个困难。事实上,我的第一个参数是一组对象,我想对每个对象调用相同的方法。