【问题标题】:Why static fields can't be accessed in class where was created on by specifying the class name为什么在通过指定类名创建的类中无法访问静态字段
【发布时间】:2014-07-13 12:06:52
【问题描述】:
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;
   }
}

我的问题是为什么静态可以在使用实例的其他类中访问,但不能在创建它的类中访问?

【问题讨论】:

    标签: c# .net oop static


    【解决方案1】:

    this keyword 用于引用类的当前实例,但由于这些字段是静态的,因此它们不与任何实例关联。尝试删除this

    private void test()
    {
        CurrentFrameRate = 30;
    }
    

    或者通过可选地指定类名,像这样:

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

    请注意,在这两种情况下,以及在您为main 类显示的代码中,您从未真正引用过Configuration 类的任何实例。您正在引用类本身的静态字段。

    【讨论】:

    • @IvandroIsmael 我认为 实际 代码在方法中包含它,但我觉得为了未来读者的利益指出这一点很重要。我已更新我的答案以反映您更新后问题中的代码。
    【解决方案2】:

    静态字段属于类型本身,总是通过指定类型名称来引用,如

    Configuration.CurrentFrameRate
    

    但是,在类型本身中有一个代码快捷方式,您可以在其中省略Configuration. 部分,并将其用作CurrentFrameRate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多