Строка не передается в другой класс в С# wpfC#

Место общения программистов C#
Anonymous
Строка не передается в другой класс в С# wpf

Сообщение Anonymous »

РЕДАКТИРОВАТЬ: я решил эту проблему, передав строку через общедоступную статическую строку: я изменил общедоступную статическую строку autosavePath на общедоступную статическую строку autosavePath. Во втором классе я заменил публичную строку атрибутыFilePath = «ничего»; с общедоступной статической строкой 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();
}

}
}
вот что показали журналы:
07.06.2024 15:24:48: функция rerangeAutosaves вернула «успех»; установка dirsExist = true
07.06.2024 15:06:48: autosavePath = C:\Users\zrylx\AppData\Local\software\settings\cloud\saves\Zrylx\ autosave3
07.06.2024 15:06:48: isValidProfile вернул true, а dirsExist вернул true
07.06.2024 15:07:00: для атрибутовFilePath не было задано ничего
6 /07/2024 15:07:00: Атрибуты каталогаFilePath не существует: ничего
также я использую MaterialDesign для wpf, и в окне сообщения отображается правильный путь к файлу (autosavePath).
Я сижу здесь часами, исследуя, изменяя свой код и создавая новые журналы, однако до сих пор совершенно не понимаю, почему это происходит. Пожалуйста, помогите.

Подробнее здесь: https://stackoverflow.com/questions/787 ... -sharp-wpf

Вернуться в «C#»