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

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

问题描述

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

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


  1. 可以Singleton类有静态方法?如果是的话那么我们如何调用该方法?

  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();

VS

Singleton.Instance.AddMethod();

另请注意,存在实现与更少的锁定等acheive同样的效果单身简单的方法。

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

重新单和静态之间的区别;单身有可能实现一个接口,让您将它传递到现有code。你也可以(因为实际上你正在做的)推迟一个单独的建筑(但仍允许访问不涉及单一实例的静态方法)。但是,是的。有很多静态和单间的交叉

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天全站免登陆