简体   繁体   English

公共静态与静态公共-有区别吗?

[英]public static vs static public - is there a difference?

sealed class PI
{
  public static float number;
  static PI()
  { number = 3.141592653F; }
  static public float val()
  { return number; }
}
  1. What's the difference between public static and static public? public static和static public有什么区别? Can they be used in any order? 可以按任何顺序使用它们吗?

  2. How would I use static public float val() ? 我将如何使用static public float val()

    Does it get executed as soon as the class is initialized? 类初始化后是否立即执行?

There's no difference. 没有区别 You're free to specify them in either order. 您可以随意以任何顺序指定它们。 However, I find that most developers tend to use public static and not static public. 但是,我发现大多数开发人员倾向于使用静态公共而非静态公共。

好吧,这就像一个人的名字=)叫Tom Mike或Mike Tom,没什么区别。

About the ordering of modifiers 关于修饰符的顺序

They can be used in any order. 它们可以以任何顺序使用。 It's just a stylistic choice which one you use. 这只是您使用的一种风格选择。 I always use visibility first, and most other code does too. 我总是首先使用可见性,大多数其他代码也使用可见性。

About the second question: 关于第二个问题:

static public float val()

This is just a static function. 这只是一个静态函数。 You call it with PI.val() . 您可以使用PI.val()调用它。 You just don't need an instance of the class to call it, but call it on the class directly. 您只是不需要类的实例来调用它,而是直接在类上调用它。 A static function does not receive a this reference, can't be virtual, it's just like a function in a non OOP language, except that it's using the class as namespace. 静态函数不会收到this引用,也不能是虚拟的,就像非OOP语言中的函数一样,只是它使用类作为名称空间。

There is no difference. 没有区别。 Their order is not important with respect to each other 彼此之间的顺序并不重要

To answer your second question, it should probably be written as 要回答您的第二个问题,可能应该写成

public static class Pi
{
    private static float pi = 0;

    public static float GetValue()
    {
        if (pi == 0)
            pi = 3.141592653F;   // Expensive pi calculation goes here.

        return pi;
    }
}

And call it thusly: 并这样称呼它:

float myPi = Pi.GetValue();

The reason for writing such a class is to cache the value, saving time on subsequent calls to the method. 编写此类的原因是为了缓存该值,从而节省了后续调用该方法的时间。 If the way to get pi required a lot of time to perform the calculations, you would only want to do the calculations once. 如果获取pi的方法需要大量时间来执行计算,则只需要执行一次计算即可。

With regards to the second question: The method is available without an instance of a class, it could be called thusly: 关于第二个问题:该方法在没有类实例的情况下可用,因此可以这样调用:

PI.val();

Because the class only has static members, the class should probably be a static class, and then it could never get initialized. 因为该类仅具有静态成员,所以该类可能应该是静态类,因此永远无法初始化。

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

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