简体   繁体   English

如何从静态类返回类实例?

[英]How to return class instance from static class?

I want use a static class that must contains global variables, so I can access to all application controls simply from a variable.我想使用一个必须包含全局变量的静态类,这样我就可以简单地从一个变量访问所有应用程序控件。 Actually I've this implementation:其实我有这个实现:

public static class Globals
{
    public static HeadToHead Head2Head
    {
       get { return Resources.Controls.HeadToHead; }
    }
}

in the case above, I want return the instance of HeadToHead control, the control look like this:在上面的例子中,我想返回HeadToHead控件的实例,控件如下所示:

public partial class HeadToHead : UserControl
{
    public static int HomeId = 0;

}

my goal is to access to the static variables of this control, like: Globals.Head2Head.HomeId我的目标是访问此控件的静态变量,例如: Globals.Head2Head.HomeId

but I get this error on this line: get { return Resources.Controls.HeadToHead; }但我在这一行收到此错误: get { return Resources.Controls.HeadToHead; } get { return Resources.Controls.HeadToHead; }

HeadToHead is a type which is not valid in the given context HeadToHead 是在给定上下文中无效的类型

You're returning what looks like a type from a property that seems to be declaring an instance of that type.您正在从似乎声明该类型的实例的属性中返回看起来像是类型的内容。 If you truly want to return that type, there's syntax for that (I don't remember any more, I think in c# it's classname.type).如果你真的想返回那个类型,有它的语法(我不记得了,我认为在 c# 中它是 classname.type)。 If you want to return an instance, then you need to get that instance from somewhere.如果您想返回一个实例,那么您需要从某个地方获取该实例。

As an aside, static instances of UI controls are a bad idea, and a code smell.顺便说一句,UI 控件的静态实例是一个坏主意,并且是代码异味。

You have to instantiate an instance of the type and return that.您必须实例化该类型的实例并返回该实例。 As you want a single global instance you could use the static constructor.当您想要一个全局实例时,您可以使用静态构造函数。

public static class Globals {

    static Globals(){
       Head2Head = new Resources.Controls.HeadToHead();
    }

    public static HeadToHead Head2Head { get; private set; }
}

There are few situations in which you would actually want to do this but common static settings that do not change in the life of the application might be one of them.在少数情况下,您实际上想要这样做,但在应用程序的生命周期中不会更改的常见静态设置可能是其中之一。 As HeadToHead inherits from UserControl that does not really seem to be the case, an instance of a UserControl should ideally never be static.由于HeadToHead继承自UserControl ,但实际情况似乎并非如此,因此UserControl的实例理想情况下不应是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM