c# - 引用其他函数 C# 创建的实例的函数

标签 c# instance

我有一个可能很愚蠢的问题,但我是 C# 的新手,所以请原谅我的无礼。我想知道一个函数是否可以引用另一个函数创建的实例。

我包含了一个示例代码来说明我的意思:

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.");
        }
    }
}

我可以使用什么来引用 Referent.Refer 函数中的“实例”实例(由 Instantiator.Instantiate 函数创建)?

在此先感谢您的中肯意见!

最佳答案

使Instantiator完成后返回类

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

关于c# - 引用其他函数 C# 创建的实例的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167806/

相关文章:

select - Grails - 如何在更改选择后更新 GSP?

python - 让 Python 对象的单个实例监听 future 参数的顺序

c# - 在大型 Asp.net 应用程序中更改每个控件,如 TextBox 的最大长度

c# - binaryreader 内存泄漏 Windows Phone 8

c# - 使用 JSON.Net 编写属性名称

python - 为什么 python 字典在我启动一个新的类实例时会记住前一个实例的值?

java - 类实例直接协同工作

c# - 超时关闭在控制台中无法关闭启动画面

c# - Xamarin.iOS NSUrlSession 不适用于 iOS 8

c# - 使用 netMsmqBinding 与 IIS 托管绑定(bind)时,WCF 服务托管失败