【问题标题】:How to access an object in another method in C#? [duplicate]如何在 C# 中以另一种方法访问对象? [复制]
【发布时间】:2020-09-24 11:11:33
【问题描述】:

我正在尝试访问玩家的分数并在用户回答正确问题时更新它?但是,当我引用实例化对象时,会出现超出范围的错误。

如果问题正确,我会尝试在 TriviaItem 中增加用户分数。

这是我的 repl.it 链接:https://repl.it/@tylermorales1/TriviaGame#Game.cs

// Game.cs
using static System.Console;
using System;

namespace Trivia
{
  class Game
    {
      public Game()
      {
        Setup();
        Play();
        GameOver();
      }

      public void Setup()
      {
        // get player name 
        Player user = new Player();
        user.score = 0;
      }

      public void Play()
      {
          // check answer
          playerInput = ReadLine();
          WriteLine(question.checkAnswer(playerInput));
        }
      }
      
      public void GameOver(){
        // Show total score
        WriteLine($"Your score is: ");
      }
    }
}

using static System.Console;

class TriviaItem
{
  public string Question;
  public string Answer;

  //overloaded constructor
  public TriviaItem(string question, string answer)
  {
    Question = question;
    Answer = answer;
  }

  // check answer
  public string checkAnswer(string userInput)
  {
    if(this.Answer.ToLower() == userInput.ToLower()) {
      user.score++;
      return "Correct!!!";
    } else {
      return $"\nIncorrect :(\n The correct answer is: '{this.Answer}'\n Your answer was: '{userInput}'";
    }
  }     
}
namespace Trivia
{
    class Player
    {
        public string name = "Anonymous Person";
        public int score = 0;
    }
}

【问题讨论】:

  • 另一个设计问题是 TriviaItem 根本不应该与用户打交道。 checkAnswer 简单返回布尔值,由Game 类根据返回值增加分数。

标签: c# class object


【解决方案1】:

在您的class Game 中创建一个private Player user 变量并在您的Setup() 函数中实例化。

外观示例:

class Game{
    private Player user;

    public void Setup(){
        user = new Player();
    }
}

那么你就可以在整个 Game 类中访问user.score

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2014-02-20
    相关资源
    最近更新 更多