【问题标题】:Issue with object reference being required for the non-static field非静态字段需要对象引用的问题
【发布时间】:2013-02-16 02:53:02
【问题描述】:

我有以下代码,我的问题是,当我引用变量时,它给了我错误:每个变量的非静态字段、方法或属性都需要对象引用。我知道这与我的 public int 和 public double 是非静态的有关,但我不知道如何解决它。有人可以告诉我吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace homework3
{
    public class Program
    {

           public int number_of_scores;
           public double score, total_score = 0, high_score, low_score, average;


    } 
    class Class1{

        static void Main(string[] args){


            Console.Write("please enter the number of scores that you
wish to process? ");
            Program.number_of_scores = int.Parse(Console.ReadLine());

            Console.Write("Please enter score " + 1 + " ");
            Program.score = double.Parse(Console.ReadLine());

            Program.high_score = Program.score;
            Program.low_score = Program.score;

            Program.total_score = Program.total_score = Program.score;


            for (int i = 2; i <= number_of_scores; i++);
         }  
 }

     class class2
        {
         static void Main(string[] args){


                Console.Write("Please enter score " + i + " ");
                Program.score = double.Parse(Console.ReadLine());

                Program.total_score = Program.total_score + Program.score;

                if(Program.score > Program.high_score)
                Program.high_score = Program.score;

                if(Program.score < Program.low_score)
                Program.low_score = Program.score;
        }
            }

      class Class3
     {
          static void Main(string[] args){

          Program.average = Program.total_score / Program.number_of_scores;

          Console.WriteLine("you entered " + Program.number_of_scores +
 " scores");
          Console.WriteLine("The high score is " + Program.high_score);
          Console.WriteLine("The low score is " + Program.low_score);
          Console.WriteLine("the average score is " + Program.average);
     }
      }

【问题讨论】:

    标签: c# visual-studio-2010


    【解决方案1】:

    行内:

    Program.number_of_scores = int.Parse(Console.ReadLine());
    

    您尝试从 static 方法引用 instance 变量 number_of_scores

    让它工作的最简单的方法是将number_of_scores声明为静态:

    static public int number_of_scores;
    

    您的其他一些字段也有同样的问题。

    【讨论】:

      【解决方案2】:

      您需要将 number_of_scores 和 score(以及其他变量)声明为静态的。

      public static int number_of_scores;
      public static double score, //etc
      

      【讨论】:

      • 我想我要问的是:我如何将它们声明为静态的?或者你会怎么做?我似乎不能像其他人那样做,因为他们是公开的,他们对我来说很奇怪,我对此不是很熟悉。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多