I have a class defining several functions with the same signature
public class MyClass
{
public string MyParam1() ...
public string MyParam2() ...
...
}
From another class I want to call a method passed as parameter on an object passed as parameter
void MyFunction(MyClass anObject, Func<string> aMethod)
{
string val = ??? // Here call aMethod on anObject
}
I'm pretty sure it's possible to do this using reflection, but is there a not to difficult way to do it ?
In fact I have a set of objects, not a single object, it's why I cannot call directly the method of the object.
If you pass the instance method as a function, it is already bound to the instance , so your anObject
is useless in this case.
This code already operates on this
:
MyFunction(null, this.DoSomething);
Here val
will always be the result of this.DoSomething
in the context of the caller:
string val = aMethod();
What you can do instead of passing the instance method around, is create a static method that has a parameter for anObject
. In that way, your static method can do instance specific tasks.
public string MyParam2(MyClass instance) { }
void MyFunction(MyClass anObject, Func<MyClass, string> aMethod)
{
string val = aMethod(anObject);
}
You don't need to worry about anObject
as aMethod
is already bound to an instance . The definition of a delegate is that it's a reference to an instance of a method .
Therefore the following should suffice:
void MyFunction(Func<string> aMethod)
{
string val = aMethod();
}
If you really want to call a given method on a object, the don't use Func
but pass in the object and the name of the method:
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);
}
When executed, this will print
Hello
as it will call the SayHello
method on the Test
instance t
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.