如何访问 Singleton 类的静态方法? [英] How to access Singleton class's static method?

查看:73
本文介绍了如何访问 Singleton 类的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对单例类有些困惑,以下是我的一些观点:

I have some confusion with singleton class, below are my some points:

  1. 单例类可以有静态方法吗?如果是,那么我们如何调用这些方法?
  2. 静态类和单例类之间的主要区别是什么?

我已经按如下方式创建了我的单例类:

I have created my singleton class as follows:

 public class Singleton
    {
        private static  Singleton _instance = null;
        private static object chekLock = new object();
        private Singleton()
        {}

        public static Singleton Instance
        {
            get
            {
                lock (chekLock)
                {
                    if (_instance == null)
                        _instance = new Singleton();
                    return _instance;
                }
            }
        }

        public static void StaticAddMethod()
        {
            Console.WriteLine("Add Method");
        }

        public void AddMethod()
        {
            Console.WriteLine("Add Method");
        }
    }

在上面的类结构中,我创建了两个方法,一个是静态的,第二个是非静态的,当我尝试访问静态方法时,它给了我编译时错误.

In Above class structure I have created two method one is Static and second is non static, When I am trying to access Static Method it gives me compile time error.

如何使用单例类的静态方法?

How can I use static method of singleton class?

推荐答案

您打算如何访问它?要访问静态方法,请使用类型名称:

How are you trying to access it? To access a static method you use the type name:

Singleton.StaticAddMethod();

对比

Singleton.Instance.AddMethod();

另请注意,有一些更简单的方法可以实现单例,但可以通过更少的锁定等实现相同的效果.

Note also that there are simpler ways of implementing singletons that acheive the same effect with less locking etc.

重单例和静态的区别;单例可能会实现一个接口,允许您将其传递到现有代码中.您也可以(正如您正在做的那样)推迟单例的构建(但仍然允许访问不涉及单例实例的静态方法).但是是的:静态和单例之间有很多交叉.

Re the difference between singleton and static; a singleton might implement an interface, allowing you to pass it into existing code. You can also (as indeed you are doing) defer construction of a singleton (yet still allow access to the static methods that don't involve the singleton instance). But yes: there is a lot of crossover between static and singleton.

这篇关于如何访问 Singleton 类的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆