我用许多全局变量编写了我的程序,并且只使用了 public void 方法。 所以我想将我的方法更改为带有返回值的私有静态方法。这就是我所做的。
现在我的程序只会通过 TwitchLib 的“globalChatMessageReceived”一次,然后什么也不做。不会显示任何问题或错误,程序运行正确并保存数据,但只会执行一次。
我正在使用
FindPokemonName(MessageSplitForPokemonName[1]);
没有返回值并且
(string[] PokedexName, Boolean ChosenPokemonIsAvailable, Boolean ChosenPokemonIsNoStarter, string NameOfChosenPokemon) = FindPokemonName(MessageSplitForPokemonName[1]);
有返回值。
这是带有全局变量且无返回值的代码:
public void FindTrainerID(string TrainerID, string ChatDisplayName)
{
TrainerVorhanden = false;
if (File.Exists(@"C:\txt\trainer\" + TrainerID + ".txt"))
{
string FoundTrainer = File.ReadAllText(@"C:\txt\trainer\" + TrainerID + ".txt");
Trainer = FoundTrainer.Split('\\');
TrainerVorhanden = true;
}
}
这就是我现在对返回值所做的事情:
private static (string[] Trainer, bool TrainerAvailable) FindTrainerID(string TrainerID)
{
string[] Trainer = new string[5];
Boolean TrainerAvailable = false;
if (File.Exists(@"C:\txt\trainer\" + TrainerID + ".txt"))
{
string FoundTrainer = File.ReadAllText(@"C:\txt\trainer\" + TrainerID + ".txt");
Trainer = FoundTrainer.Split('\\');
TrainerAvailable = true;
}
return (Trainer, TrainerAvailable);
}
我尝试了该程序,但没有使用带返回值的方法。该程序通过 TwitchLib 方法“globalChatMessageReceived”持续运行。
如果我使用返回值,那么此后它不会执行任何操作。
您可能会发现使用类比返回这样的元组更容易。
例如,声明这个数据类:
class TrainerInfo {
public string[] Trainer { get; set;}
public bool TrainerAvailable { get; set;}
}
然后尝试一下:
static TrainerInfo FindTrainerID(string TrainerID) {
var result = new TrainerInfo();
string trainerPath = $@"D:\junk\trainer\{TrainerID}.txt";
if (File.Exists(trainerPath)) {
string FoundTrainer = File.ReadAllText(trainerPath);
result.Trainer = FoundTrainer.Split('\\').ToArray();
result.TrainerAvailable = true;
}
return result;
}
也值得深思:
Trainer
绝对have是一个数组,还是可以使用更动态的集合类型(例如List<string>
)?