繁体   English   中英

是否静态引用了Class的“ this”实例,而没有实例化Class的实例?

[英]Static reference to 'this' instance of a Class without ever instantiating an instance of the Class?

我在Unity3D中使用C#进行编程,并且在遇到类似类型的代码时正在学习有关对象池的知识:

public class MyClass : Object
{
    public static MyClass current;

    void Awake()
    {
        current = this;
    }

    public void SomeMethod()
    {

    }
}

public class Other
{
    void AnotherMethod()
    {
        MyClass.current.SomeMethod();
    }
}

现在,类MyClass是非静态的,但是对其实例“ this”的引用“当前”是(静态)。 通过使用其他类中对“ this”实例的静态引用“当前”,我可以调用公共非静态方法并访问所有其他公共非静态变量。

但是,如果我从未创建MyClass类的实例,则静态引用指向什么?

Class具有一个静态字段,其中包含对自身单个实例的引用。 如果您尝试从Other类访问它而未为current分配有效值,则会得到NullReferenceException

实例可以在任何地方(因为它是公共静态字段)创建,例如在某些启动代码处。 使用单例模式,该类将具有一个私有构造函数和一个GetInstance (或GetCurrent )方法,该方法将在该类被调用且current为null时创建该类的实例。

您不能在没有实例的情况下调用Awake() ,因此它可以像这样初始化:

static void Main()
{
    // without this call, x.AnotherMethod will throw an exception.
    new Class().Awake();

    var x = new Other();
    x.AnotherMethod();
}

给定的模式应尽可能避免使用,因为它具有全局变量的含义。 您无法在任何时间确定current字段所指向的实例。 如果类Class没有内部状态,则可以将其标记为静态并且仅公开静态方法。

它不会指向任何内容,因此将引发null引用异常

暂无
暂无

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

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