How Do I capture a variable?
Alternatively, can I store a reference to an object reference?
Normally, a method can alter a variable outside of it using ref
keyword.
void Foo(ref int x)
{
x = 5;
}
void Bar()
{
int m = 0;
Foo(ref m);
}
This is clear and straight-forward.
Now let's consider a class to achieve the same thing:
class Job
{
// ref int _VarOutsideOfClass; // ?????
public void Execute()
{
// _VarOutsideOfClass = 5; // ?????
}
}
void Bar()
{
int m = 0;
var job = new Job()
{
_VarOutsideOfClass = ref m // How ?
};
job.Execute();
}
How do I write it correctly ?
Comments: I can't make it a method with an ref
argument, because typically Execute()
will called somewhat later in a different thread, when it comes up in the queue.
Currently, I made a prototype with plenty of lambdas:
class Job
{
public Func<int> InParameter;
public Action<int> OnResult;
public void Execute()
{
int x = InParameter();
OnResult(5);
}
}
void Bar()
{
int m = 0;
var job = new Job()
{
InParameter = () => m,
OnResult = (res) => m = res
};
job.Execute();
}
... but maybe there is a better idea.