编辑:我通过将字符串传递给公共静态字符串解决了这个问题:我将公共字符串自动保存路径更改为公共静态字符串自动保存路径。在第二节课中,我替换了公共字符串attributesFilePath =“nothing”;公共静态字符串 autosavePath = $"{careerProfile.autosavePath}";
我正在创建一个软件,它基本上根据用户输入的配置文件用户名修改 .json 文件。所有代码都根据输入的用户名成功检索 .json 文件的文件位置。但是,无论我做什么,我都无法将“autosavePath”字符串从第一个类(保存路径)传递到第二个类。此外,我还设置了一个日志系统来尝试跟踪发生的情况,一旦第二类中的代码开始,字符串就保持为空,而字符串保存第一类中的正确路径。
第一堂课:
public class firstClass
{
public bool isValidProfile = false;
public bool dirsExist = false;
public string autosavePath = "";
public async Task checkProfileAsync(MainWindow mw)
{
rearrangeSaveDirs rearrangeDirs = new rearrangeSaveDirs();
playerAttributes playerAttributes = new playerAttributes();
await Task.Run(() =>
{
if (Directory.Exists(profilePath))
{
Debug.WriteLine($"profile {profileName} exists at {profilePath}");
logger.log($"profile {profileName} exists at {profilePath}");
isValidProfile = true;
logger.log("isValidProfile = true");
//make sure that the autosave files were successfully rearranged
bool success = rearrangeDirs.rearrangeAutosaves(this);
if (success)
{
logger.log("rearrangeAutosaves function returned 'success'; setting dirsExist = true");
dirsExist = true;
}
Task.Delay(1500).Wait();
}
else
{
Debug.WriteLine($"profile {profileName} was not found at {profilePath}");
logger.log($"profile {profileName} was not found at {profilePath}");
isValidProfile = false;
logger.log("isValidProfile = false");
}
}
}
});
if (isValidProfile == true && dirsExist == true)
{
autosavePath = rearrangeDirs.keptAutosaveDir;
logger.log($"autosavePath = {autosavePath}");
logger.log("isValidProfile returned true and dirsExist returned true");
await Task.Run(() =>
{
Thread.Sleep(5500);
});
playerAttributes.attributesFilePath = autosavePath;
MessageBox.Show($"{autosavePath}");
}
}
}
这是第二堂课:
public class playerAttributes
{
//file path to the attributes file
public string attributesFilePath = "nothing";
public void modifyAttributes(string option, double value)
{
//modify the playerAttributes.json file correspondingly to what the user selected
logger.log($"attributesFilePath was set to {attributesFilePath}");
if (Directory.Exists(attributesFilePath))
{
//continue function
}
else
{
logger.log($"Directory attributesFilePath does not exist: {attributesFilePath}");
errorBox.sendMSB();
}
}
}
这是日志显示的内容: 6/07/2024 3:24:48 PM:rearrangeAutosaves 函数返回“成功”;设置 dirsExist = true
6/07/2024 3:06:48 PM: autosavePath = C:\Users\zrylx\AppData\Local\software\setting