简体   繁体   English

为什么可以调用非静态类的静态方法?

[英]Why is possible to call static methods of a non-static class?

Taking into consideration the following class structure: 考虑以下类结构:

[PUBLIC NON-STATIC CLASS] [公共非静态类别]

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public static void Play() //STATIC METHOD
    {
        print("Play some audio!");
    }

}

ANOTHER CLASS CALLING: 另一个类调用:

using UnityEngine;
using System.Collections;

public class TestClass : MonoBehaviour {

    // Use this for initialization
    void Start () {
        GameManager.Play();
    }

    // Update is called once per frame
    void Update () {

    }
}

Because it is possible to call this method without instantiating the class GameManager? 因为可以在不实例化GameManager类的情况下调用此方法?

From here 这里

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated 静态类与非静态类基本相同,但有一个区别:静态类无法实例化

The fact that it's not a static class doesn't affect the way static methods can be used. 它不是静态类的事实并不影响静态方法的使用方式。

Static methods are often used in a non-static class for utility methods. 静态方法通常在实用程序方法的非静态类中使用。 They can also be used for masking modifiers and constructors on immutable types by returning a new object from the requested manipulation. 通过从请求的操作中返回新对象,它们还可用于掩盖不可变类型的修饰符和构造函数。 See java String. 请参阅java String。

The difficulty comes from the fact that 'static' has a slightly different meaning for methods and for classes. 困难来自这样一个事实,即“静态”对于方法和类的含义略有不同。

  1. Static classes cannot be instantiated 静态类无法实例化
  2. Static methods are associated with the class rather than objects, so you don't need to create an object to call a static method. 静态方法与类而不是对象相关联,因此您无需创建对象来调用静态方法。 However, it does not matter if the class itself is static or not. 但是,类本身是否是静态的都没有关系。

See the relevant documentation here . 请参阅此处的相关文档。

当方法声明为static时 ,可以在创建其类的任何对象之前对其进行访问,并且无需引用任何对象,并且非静态类也可以包含静态方法。

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

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