Let's take class A
with private methods f()
and g()
. Let class B
have public method h
. Is it possible to pass pointer/delegate pointing to A.g
from method A.f
to B.h
?
Consider the following code:
Class B
{
public B() {}
public h(/*take pointer/delegate*/)
{
//execute method from argument
}
}
Class A
{
private int x = 0;
private void g()
{
x = 5;
}
private void f()
{
B b = new B();
b.h(/*somehow pass delegate to g here*/);
}
}
After A.f()
is called I would like A.x
to be 5
. Is it possible? If so, how?
You could create an Action
argument to your method:
public h(Action action)
{
action();
}
and then call it like this:
b.h(this.g);
Possibly worth noting that there are generic versions of Action
that represent methods with parameters. For example, an Action<int>
would match any method with a single int
parameter.
Yes it is.
class B
{
public B()
{
}
public void h(Action func)
{
func.Invoke();
// or
func();
}
}
class A
{
private int x = 0;
private void g()
{
x = 5;
}
private void f()
{
B b = new B();
b.h(g);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With