I want to send actions through a parameter using the following simplified code below.
public class Class1
{
public Class2 myClass = null;
public static void Start()
{
Class3.Run(myClass.WriteText("Hi"));
}
}
public class Class2
{
public Class2()
{
}
public void WriteText(string text)
{
Console.Writeline(text);
}
}
public class Class3
{
public static void Run(Action action)
{
//Some code that causes a 60 second delay
action();
}
}
This code shows that if i call for Start() in Class1 then I want to send an action called WriteText() from Class2 to Class3 Run().
However, since Class2 myClass = null at some possible moments the passing through does not work because myClass is null. Ofcourse.
I want to be able to pass through the action WriteText even if its class is null. Then wait in Class3 for 60 seconds and perform the action. If myClass is still null then ofcourse dont send.
I have trouble explaining my situation, im sorry. The code above here is what I am trying, but ofcourse this does not work.
CodePudding user response:
The code example you've given is perhaps a poor example of what you're trying to achieve, but I think I have the gist of it.
Actions, like all delegate types, are closures that encapsulate both a method reference and a reference to an object instance - although for closures over static methods that instance reference may be null. Once you create an instance of a closure there's no way to modify the object it refers to. If you're expecting that myClass will change then you'll have to take a more indirect approach, using a method that references the myClass field in Class1:
Class3.Run(() => myClass.WriteText("Hi"));
The lambda expression will be called when the 'some code that causes a 60 second delay' has completed, and it will fetch the current value of myClass at that point in time. You'll have to change myClass to be a static field to access it without a reference to an instance of Class1 of course, otherwise that won't compile either. And you'll have to set myClass somewhere in the process or it'll error on that line.
CodePudding user response:
why not try something like:
public class Class1
{
public static Class2 myClass = null;
public static void Start()
{
Class3.Run(() => myClass?.WriteText("Hi"));
}
}
the '?' will make sure function is not called if instance is null :)
