【问题标题】:How to send value from one class to another in C#?如何在 C# 中将值从一个类发送到另一个类?
【发布时间】:2018-10-03 17:09:44
【问题描述】:

我有 void Start(),其中声明了字符串 snapshotJson,我有私有 void LoadGameData() 需要调用 snapshotJson 的值。声明 snapshotJson public 不起作用,我认为是因为无效。从我读到的内容来看,我应该使用 getter 和 setter,但我不知道它们是如何工作的,而且我读过的每一篇解释它的指南都让它看起来很简单,但它们解释得如此简单,我不明白我到底是怎么做到的我应该使用它,或者在使用 get/set 函数后如何调用该值。

谁能解释我如何将变量从一个类传递到另一个类?在我的代码中,LoadGameData 无法调用 snapshotJson 的值,我不确定我缺少什么。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;

using Firebase;
using Firebase.Unity.Editor;
using Firebase.Database;
using System;

public class DataController : MonoBehaviour
{

private RoundData[] allRoundData;
private PlayerProgress playerProgress;

[Serializable]
public class FirebaseStart : MonoBehaviour
{
    public string snapshotJson { get; set; }

    void Start()
    {


            // Set up the Editor before calling into the realtime database.

FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://FIREBASEDATABASE");

        // Get the root reference location of the database.
        DatabaseReference reference = 
FirebaseDatabase.DefaultInstance.RootReference;

        FirebaseDatabase.DefaultInstance
         .GetReference("allRoundData")
          .GetValueAsync().ContinueWith(task => {
              if (task.IsFaulted)
              {
                  // Handle the error...
              }
              else if (task.IsCompleted)
              {
                 //  DataSnapshot snapshot = task.Result;
                snapshotJson = JsonUtility.ToJson(task.Result);

              }
          });
    }
}

// Use this for initialization
void Start ()
{
    DontDestroyOnLoad(gameObject);
    LoadGameData();
    LoadPlayerProgress();

    SceneManager.LoadScene("MenuScreen");
}

public RoundData GetCurrentRoundData()
{
    return allRoundData [0];
}

public void SubmitNewPlayerScore(int newScore)
{
    if (newScore > playerProgress.highestScore)
    {
        playerProgress.highestScore = newScore;
        SavePlayerProgress();
    }
}

public int GetHighestPlayerScore()
{
    return playerProgress.highestScore;
}
// Update is called once per frame
void Update () {

}

private void LoadPlayerProgress()
{
    playerProgress = new PlayerProgress();

    if (PlayerPrefs.HasKey("highestScore"))
    {
        playerProgress.highestScore = PlayerPrefs.GetInt("highestScore");
    }
}
private void SavePlayerProgress()
{
    PlayerPrefs.SetInt("highestScore", playerProgress.highestScore);
}

public void LoadGameData()
{

    GameData loadedData = JsonUtility.FromJson<GameData>(snapshotJson);
    Console.WriteLine(snapshotJson);
   allRoundData = loadedData.allRoundData;


}

【问题讨论】:

  • 嗨@JohnZ12,我可以看到你是 StackOverflow 的新手,我想欢迎你!如果您发现男生的回答很有帮助,您可以使用他们答案分数上的向上和向下图标来表示感谢。如果任何答案满足您的问题,请随时标记他们的答案以帮助其他有相同问题的人。干杯队友

标签: c#


【解决方案1】:

LoadGameData() 方法无法从Main() 方法访问它,因为它在该函数范围内是本地的。但是,您可以使用以下代码将 Main() 方法中的值传递给 LoadGameData()

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

public class Program
{
    private static void LoadGameData(String input) {
        // Do something inside your input here.
    }

    public static void Main() {
      Start();
    }

    public static void Start()
    {
        string snapshotJson = "Sample data";

        // Same Class Call
        LoadGameData(snapshotJson);

        // Other Class Call
        var otherClassInstance = new TestClass();

        otherClassInstance.LoadGameData(snapshotJson);
    }
}

public class TestClass {
    public void LoadGameData(String input) {
        // Do something inside your input here.
    }
}

温馨提示,如果您觉得答案有帮助,请点击复选框将其标记为已接受答案。这将帮助其他遇到与您在 atm 时遇到的相同问题的人。

【讨论】:

  • 感谢您提供的非常有帮助的答案。但是在我的情况下,void Start() 是我分配 snapshotJson 值的地方,稍后在代码中 LoadGameData() 是我需要检索它的地方。另外,我不明白字符串输入在这段代码中的作用?我是在创建一个虚拟变量,然后为它分配 snapshotJson 的值吗?
  • @JohnZ12,我通过将 main 替换为 start 来更新答案。如果您在问题上发布一些源代码会很有帮助。
  • 谢谢,我更新了我的帖子以显示代码。感谢您的帮助,我似乎仍然无法让它工作,但我用我目前所拥有的内容更新了我的代码。在代码中,尽管公开了 snapshotJson,但我无法从 LoadGameData 中检索 snapshotJson 的值。如果我在 DataController 类而不是 FirebaseStart 类中声明 snapshotJson,那么我无法从 void Start() 中设置值。
  • 我能够让它工作,我意识到我有不必要的嵌套类。我现在遇到了另一个问题,但我稍后会提出另一个问题,因为这是有效的并且我的问题得到了回答。非常感谢。
【解决方案2】:

假设您引用方法而不是类(或者更确切地说:在对象之间共享数据),这就是您可以做的。以下是您的 Game 对象的专用类的示例,SnaphopJson 是可以从任何其他对象访问和更改的公共属性。将 setter 更改为 private 将确保只能从除此类的对象之外的任何对象中读取它。

public class Game
{
    public string SnapshotJson { get; set; }

    private void LoadGameData()
    {
        // load the json, e.g. by deserialization
        SnapshotJson = "{}";
    }

    public void Start()
    {
        // access the content of your snapshot
        var s = SnapshotJson;
    }

}

【讨论】:

    【解决方案3】:

    如果变量snapshotJsonStart 方法的主体内声明,则只能在该方法内访问。如果您希望该变量可以在您的类的其他方法中访问,您可能需要将其声明为成员变量。这就是它的样子。仅当您需要在类实例之外访问 snapshotJson 的值时,您才需要将其声明为公共属性。

    public class MyClass
    {
      string snapshotJson;
    
      private void Start()
      {
          //  Assign value to snapshotJson here
          snapshotJson = "foo";
      }
    
      private void LoadGameData
      {
          //  Use value of snapshotJson here
          string s = snapshotJson;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多