Function referencing an instance created by another C # function

I have a question that might be silly, but I'm new to C #, so I apologize for my insolence. I am wondering if a function can reference an instance that was created by another function.

I include sample code to illustrate what I mean:

class Program
{
    static void Main(string[] args)
    {
        Instantiator.Instantiate();
        Referent.Refer(instance);
        Console.ReadLine();
    }
}

public class Instance
{
    public void OnInstantiated()
    {
        Console.WriteLine("I have been instantiated.");
    }
    public void OnReferred()
    {
        Console.WriteLine("I have been referred to.");
    }
}

public class Instantiator
{
    public static void Instantiate()
    {
        Instance instance = new Instance();
        instance.OnInstantiated();
    }
}

public class Referent
{
    public static void Refer(Instance instance)
    {
        if(instance != null)
        {
            instance.OnReferred();
        }
        else
        {
            Console.WriteLine("No instance to refer to.");
        }
    }
}

What can I use to be able to refer to an instance of an instance (which is created by the Instantiator.Instantiate function) in the Referent.Refer function?

Thanks in advance for your relevant comments!

+4
source share
2 answers

Make a Instantiatorreturn class when done

public class Instantiator
{
    public static Instance Instantiate()
    {
        Instance instance = new Instance();
        instance.OnInstantiated();
        return instance;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var instance = Instantiator.Instantiate();
        Referent.Refer(instance);
        Console.ReadLine();
    }
}

Instantiate() Factory Pattern"

+8

, , Singleton. , .

class Program
{
    static void Main(string[] args)
    {
        Instance.Instantiate();
        Referent.Refer(Instance.GetInstance());
        Console.ReadLine();
    }
}

public class Instance
{
    private static Instance myInstance;
    public void OnInstantiated()
    {
        Console.WriteLine("I have been instantiated.");
    }
    public void OnReferred()
    {
        Console.WriteLine("I have been referred to.");
    }
    public static void Instantiate()
    {
        myInstance = new Instance();
        myInstance.OnInstantiated();
    }
    public static Instance GetInstance()
    {
        return myInstance;
    }
}

public class Referent
{
    public static void Refer(Instance instance)
    {
        if (instance != null)
        {
            instance.OnReferred();
        }
        else
        {
            Console.WriteLine("No instance to refer to.");
        }
    }
}
+1

All Articles