如何在C#中返回静态类实例 [英] How to return a static class instance in c#

查看:68
本文介绍了如何在C#中返回静态类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个静态类的实例,但是如果不对非静态类实现单例包装,我似乎无法做到这一点–这是否可能,或者我是否缺少某些东西?

I would like to get an instance of a static class, but I can’t seem to do this without implementing a singleton wrapper on a non-static class– is this possible, or am I missing something?

public class MyInstanceTester
 {
    public MyInstanceTester()
    {
        //this is how i get a reference to a singleton now
        MyClass instance1 = MyClass.Instance();
        //this is what is would like to do (if only the compiler would let me)
        MyStaticClass instance2 = MyStaticClass.Instance();
    }
}


public class MyClass
{
    private static MyClass _myInstance;

    static MyClass()
    {
        _myInstance = new MyClass();
    }


    public static MyClass Instance()
    {
        return _myInstance;
    }

}

public static class MyStaticClass
{
    public static MyStaticClass Instance
    {
        get
        {
            return this;
        }
    }
}

推荐答案

没有静态类的实例.单例模式只是将类的相同实例返回到重复的请求.

There is no such thing as an instance of a static class. The singleton pattern simply returns the same instance of a class to repeated requests.

您可能会感到困惑:

private static MyClass _myInstance;

这只是意味着在所有实例化的对象中,以_myInstance为成员的实例化类型中,将只有一个特定对象的实例.

This simply means that there will be a single instance of that particular object among all objects instantiated of the type that have _myInstance as a member.

一些注意事项:

  • this 关键字在静态成员中无效
  • 如果您有一个静态类,那么所有成员都必须是静态的,因此 this 将永远无效
  • Singleton类不能是静态类
  • 单个子句声明一个静态成员,以帮助确保仅存在该类的单个实例
  • 请注意,对对象的静态引用不会使对象成为静态.只有参考是静态的
  • The this keyword is not valid in a static member
  • If you have a static class then all members have to be static and so this will never be valid
  • A Singleton class cannot be a static class
  • Singletons declare a single static member to help ensure that only a single instance of that class exists
  • Note that a static reference to an object does not make the object static. Only the reference is static

更多阅读:乔恩·斯基特(Jon Skeet)在实现单句方面有出色的著述.在C#深度中.我建议您阅读并研究本文,直到您不理解为止.很好.

Further reading: Jon Skeet has an excellent write up on implemeting Singletons in C# In Depth. I would suggest reading and studying this article until you grok it. It is quite good.

这篇关于如何在C#中返回静态类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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