简体   繁体   中英

Why static fields can't be accessed in class where was created on by specifying the class name

internal class Configuration
{
    public static double CurrentFrameRate = 23.976;
    public static string ListViewLineSeparatorString = "<br />";
    private void test()
    {
        // Not accessible here
        this.CurrentFrameRate = 30;
    }
}

class main
{
    // this would work just fine
   private void Test()
   {
        Configuration.CurrentFrameRate = 23.976;
   }
}

My question is why static can be accessed in other classes using instance but not in one it was created on?

The this keyword is used to refer to the current instance of a class, but since those fields are static, they are not associated with any instance. Try try removing the this :

private void test()
{
    CurrentFrameRate = 30;
}

Or by optionally specifying the class name, like this:

private void test()
{
    Configuration.CurrentFrameRate = 30;
}

Note that in both of these cases, and in the code you showed for the main class, you're never actually referencing any instances of the Configuration class. You're referencing the static fields of the class itself.

Static fields belong to type itself, and are always referenced by specifying the type name like

Configuration.CurrentFrameRate

However there is a shortcut for code inside the type itself where you are allowed to omit Configuration. part, and just use it as CurrentFrameRate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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