如何在c#中返回一个静态类实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10514729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:09:35  来源:igfitidea点击:

How to return a static class instance in c#

c#singleton

提问by PeteN

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;
        }
    }
}

采纳答案by Paul Sasik

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.

没有静态类的实例这样的东西。单例模式只是将类的相同实例返回给重复的请求。

You may be getting confused by:

您可能对以下内容感到困惑:

private static MyClass _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.

这只是意味着在所有实例化的具有 _myInstance 作为成员的类型的对象中,将有该特定对象的单个实例。

A few notes:

一些注意事项:

  • The thiskeyword is not valid in a static member
  • If you have a static class then all members have to be static and so thiswill 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
  • this关键字是不是一个静态成员有效
  • 如果您有一个静态类,则所有成员都必须是静态的,因此this永远不会有效
  • 单例类不能是静态类
  • 单例声明一个静态成员,以帮助确保该类只有一个实例存在
  • 请注意,对对象的静态引用不会使对象成为静态的。只有引用是静态的

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.

进一步阅读:Jon Skeet 有一篇关于在 C# In Depth 中实现单例的优秀文章。我建议阅读和研究这篇文章,直到你理解它。这是相当不错的。

回答by Felix K.

There is no reason to return a instance to a static class( If the class is static there is no instance ).

没有理由返回instance to a static class(如果类是静态的,则没有实例)。

You can access the class from everywhere, why returning a instanceto it? I can't imagine any reason to do this.

你可以从任何地方访问这个类,为什么要返回 ainstance呢?我想不出有什么理由这样做。

Static class usage

静态类使用

To use a static class just write it like below:

要使用静态类,只需像下面这样写:

MyStaticClass.MyMethod();
Int32 callCount = MyStaticClass.CallCount;

As you can see it doesn't even make sense to declare a variable because this would just look like this:

正如你所看到的,声明一个变量甚至没有意义,因为它看起来像这样:

MyStaticClass msc = MyStaticClass.Instance();
msc.MyMethod();
Int32 callCount = msc.CallCount;

If you want to have a shorter name you just can use:

如果你想有一个较短的名字,你可以使用:

 using MSC = MyNamespace.MyStaticClass;

回答by Connell

Your terminology is wrong. Please read the MSDN article on the static keyword.

你的术语是错误的。请阅读有关 static 关键字MSDN 文章

A static member cannot be referenced through an instance. Instead, it is referenced through the type name.

不能通过实例引用静态成员。相反,它是通过类型名称引用的。

A singletonis a class that only allows a single instance of itself. A common implimentation of this in C# is:

是一类,只允许其自身的单个实例。在 C# 中,一个常见的实现是:

public class MyClass
{
    private MyClass _value = null;

    public MyClass Value {
        get { return _value ?? (_value = new MyClass()); }
    }
}

回答by InBetween

The major problem is here:

主要问题在这里:

public static class MyStaticClass 
{     
    public static MyStaticClass Instance
    {         
         get
             {             
                  return this; //compile time error!
             }
    }
}

thisrefers to an instance of a class which does not make sense in a static class as there can be no instance of one. This by itself should make you realize that there is a fundamental error in what you are asking: "I would like to get an instance of a static class". You can not return an instance of a static class as a static class by definition can not be instantiated.

this指一个在静态类中没有意义的类的实例,因为不能有一个实例。这本身应该让您意识到您所问的问题存在根本性错误:“我想获得一个静态类的实例”。你不能返回一个静态类的实例,因为静态类的定义不能被实例化。

The singleton pattern just makes sure that you always return the sameinstance of a class. But said class can never be static.

单例模式只是确保您始终返回一个类的相同实例。但是所说的类永远不能是静态的。

回答by ispiro

From your comments I assume your solution would be:

根据您的评论,我假设您的解决方案是:

Make your class non-static. (Just keep the methods static.)

使您的课程非静态。(只需保持方法静态。)