为什么在单一实例中无法访问方法和属性

本文关键字:访问 方法 属性 单一 实例 为什么 | 更新日期: 2023-09-27 18:36:12

在MVC5应用程序上工作 Asp.net。有一个名为 ContainerAdapter 的类。在我的应用程序中,我需要多次创建此类实例。

所以我决定创建单实例进程,例如:单例。我的语法是下面的,面临从单例实例获取类 ContainerAdapter 的属性和方法的问题;

适配器类

public class ContainerAdapter
        {
            public int Age { get; set; }
            public string Name { get; set; }
            public int Id { get; set; }
            public void HelloWorld()
            {
                //
            }

            public string GetHelloWorld()
            {
                return "";
                //
            }
        }

单身 人士

public class Singleton
    {
        private static Singleton instance = null;
        private Singleton()
        {
            ContainerAdapter apapter = new ContainerAdapter();            
        }
        // Lock synchronization object
        private static object syncLock = new object();
        public static Singleton Instance
        {
            get
            {
                lock (syncLock)
                {
                    if (Singleton.instance == null)
                        Singleton.instance = new Singleton();
                    return Singleton.instance;
                }
            }
        }
    }

从单例实例想要访问方法 HelloWorld() 和 GetHelloWorld()

为什么在单一实例中无法访问方法和属性

您可能希望为此使用某种 IoC 容器,而不是手动实现您的单例。

但是,如果您真的想手动实现它,并使用锁进行同步,那么您最终会得到类似于以下代码的内容。您的单例实例是一个 ContainerAdapter,所以我只是将您的两个类合并为一个。你可以编写一些通用的单例类,但话又说回来:IoC 容器内置了这种功能。

public class ContainerAdapter
{
    public int Age { get; set; }
        public string Name { get; set; }
        public int Id { get; set; }
        public void HelloWorld()
        {
            //
        }

        private string GetHelloWorld()
        {
            return "";
            //
        }
    private static ContainerAdapter instance = null;
    // Lock synchronization object
    private static object syncLock = new object();
    public static ContainerAdapter Instance
    {
        get
        {
            lock (syncLock)
            {
                if (ContainerAdapter.instance == null)
                    ContainerAdapter.instance = new ContainerAdapter();
                return ContainerAdapter.instance;
            }
        }
    }
}