From 5ec3521d4811ad8bc6be45e89fa83d810de0abfe Mon Sep 17 00:00:00 2001 From: Kurt Date: Sat, 13 May 2017 10:20:25 -0700 Subject: [PATCH] More c#7 shorthand outs & pattern matching, other simplifications --- PKHeX.Core/Legality/Checks.cs | 7 +-- PKHeX.Core/Legality/Core.cs | 15 ++--- PKHeX.WinForms/MainWindow/Main.cs | 57 +++++++------------ PKHeX.WinForms/Subforms/SAV_Database.cs | 8 +-- .../Save Editors/Gen5/CGearBackground.cs | 7 ++- PKHeX.WinForms/Util/WinFormsUtil.cs | 2 +- Tests/PKHeX.Tests/PKM/PKMTests.cs | 8 +-- 7 files changed, 44 insertions(+), 60 deletions(-) diff --git a/PKHeX.Core/Legality/Checks.cs b/PKHeX.Core/Legality/Checks.cs index 53f066387..b46a3f609 100644 --- a/PKHeX.Core/Legality/Checks.cs +++ b/PKHeX.Core/Legality/Checks.cs @@ -2316,8 +2316,7 @@ private void verifyForm() } if (pkm.Format == 7 && pkm.AltForm != 0 ^ Type == typeof(MysteryGift)) { - var gift = EncounterMatch as WC7; - if (gift != null && gift.Form != pkm.AltForm) + if (EncounterMatch is WC7 gift && gift.Form != pkm.AltForm) { AddLine(Severity.Invalid, V307, CheckIdentifier.Form); return; @@ -2507,8 +2506,8 @@ private void verifyMiscG1() if ((EncounterMatch as EncounterStatic)?.Version == GameVersion.Stadium || EncounterMatch is EncounterTradeCatchRate) // Encounters detected by the catch rate, cant be invalid if match this encounters { AddLine(Severity.Valid, V398, CheckIdentifier.Misc); } - if (((pkm.Species == 149) && (catch_rate == PersonalTable.Y[149].CatchRate)) || - (Legal.Species_NotAvailable_CatchRate.Contains(pkm.Species) && (catch_rate == PersonalTable.RB[pkm.Species].CatchRate))) + if (pkm.Species == 149 && catch_rate == PersonalTable.Y[149].CatchRate || + Legal.Species_NotAvailable_CatchRate.Contains(pkm.Species) && catch_rate == PersonalTable.RB[pkm.Species].CatchRate) { AddLine(Severity.Invalid, V396, CheckIdentifier.Misc); } else if (!EvoChainsAllGens[1].Any(e => catch_rate == PersonalTable.RB[e.Species].CatchRate || catch_rate == PersonalTable.Y[e.Species].CatchRate)) { AddLine(Severity.Invalid, pkm.Gen1_NotTradeback? V397: V399, CheckIdentifier.Misc); } diff --git a/PKHeX.Core/Legality/Core.cs b/PKHeX.Core/Legality/Core.cs index 1c49c09fd..a6cec8a96 100644 --- a/PKHeX.Core/Legality/Core.cs +++ b/PKHeX.Core/Legality/Core.cs @@ -2079,8 +2079,7 @@ internal static List getEncounter12(PKM pkm) if (g1 == null || g2 == null) return new List { g1 ?? g2 }; - var t = g1.Encounter as EncounterTrade; - if (t != null && getEncounterTrade1Valid(pkm)) + if (g1.Encounter is EncounterTrade && getEncounterTrade1Valid(pkm)) return new List { g1 }; // Both generations can provide an encounter. Return highest preference @@ -2949,14 +2948,10 @@ internal static string getEncounterTypeName(PKM pkm, object Encounter) var t = Encounter; if (pkm.WasEgg) return "Egg"; - if (t is IEncounterable) - return ((IEncounterable)t).Name; - if (t is IEncounterable[]) - { - var arr = (IEncounterable[])t; - if (arr.Any()) - return arr.First().Name; - } + if (t is IEncounterable e) + return e.Name; + if (t is IEncounterable[] arr && arr.Length != 0) + return arr[0].Name; if (t is int) return "Unknown"; return t?.GetType().Name ?? "Unknown"; diff --git a/PKHeX.WinForms/MainWindow/Main.cs b/PKHeX.WinForms/MainWindow/Main.cs index e6a7069e7..5fa76d886 100644 --- a/PKHeX.WinForms/MainWindow/Main.cs +++ b/PKHeX.WinForms/MainWindow/Main.cs @@ -305,8 +305,8 @@ private void loadConfig(out bool BAKprompt, out bool showChangelog, out int lang // Version Check if (Settings.Version.Length > 0) // already run on system { - int lastrev; int.TryParse(Settings.Version, out lastrev); - int currrev; int.TryParse(Resources.ProgramVersion, out currrev); + int.TryParse(Settings.Version, out int lastrev); + int.TryParse(Resources.ProgramVersion, out int currrev); showChangelog = lastrev < currrev; } @@ -350,11 +350,10 @@ private void mainMenuOpen(object sender, EventArgs e) // Detect main string cgse = ""; - string path; string pathCache = CyberGadgetUtil.GetCacheFolder(); if (Directory.Exists(pathCache)) cgse = Path.Combine(pathCache); - if (!PathUtilWindows.detectSaveFile(out path, cgse)) + if (!PathUtilWindows.detectSaveFile(out string path, cgse)) WinFormsUtil.Error(path); if (path != null) @@ -415,11 +414,11 @@ private void mainMenuAbout(object sender, EventArgs e) new About().ShowDialog(); } // Sub Menu Options + private Form getFirstFormOfType() => Application.OpenForms.Cast
().FirstOrDefault(form => form is T); private void mainMenuBoxReport(object sender, EventArgs e) { - var z = Application.OpenForms.Cast().FirstOrDefault(form => form.GetType() == typeof(frmReport)) as frmReport; - if (z != null) - { WinFormsUtil.CenterToForm(z, this); z.BringToFront(); return; } + if (getFirstFormOfType() is frmReport z) + { z.CenterToForm(this); z.BringToFront(); return; } frmReport ReportForm = new frmReport(); ReportForm.Show(); @@ -429,17 +428,15 @@ private void mainMenuDatabase(object sender, EventArgs e) { if (ModifierKeys == Keys.Shift) { - var c = Application.OpenForms.Cast().FirstOrDefault(form => form.GetType() == typeof(KChart)) as KChart; - if (c != null) - { WinFormsUtil.CenterToForm(c, this); c.BringToFront(); } + if (getFirstFormOfType() is KChart c) + { c.CenterToForm(this); c.BringToFront(); } else new KChart().Show(); return; } - var z = Application.OpenForms.Cast().FirstOrDefault(form => form.GetType() == typeof(SAV_Database)) as SAV_Database; - if (z != null) - { WinFormsUtil.CenterToForm(z, this); z.BringToFront(); return; } + if (getFirstFormOfType() is SAV_Database z) + { z.CenterToForm(this); z.BringToFront(); return; } if (Directory.Exists(DatabasePath)) new SAV_Database(this).Show(); @@ -449,12 +446,10 @@ private void mainMenuDatabase(object sender, EventArgs e) } private void mainMenuMysteryDM(object sender, EventArgs e) { - var z = Application.OpenForms.Cast().FirstOrDefault(form => form.GetType() == typeof(SAV_MysteryGiftDB)) as SAV_MysteryGiftDB; - if (z != null) - { WinFormsUtil.CenterToForm(z, this); z.BringToFront(); return; } + if (getFirstFormOfType() is SAV_MysteryGiftDB z) + { z.CenterToForm(this); z.BringToFront(); return; } new SAV_MysteryGiftDB(this).Show(); - } private void mainMenuUnicode(object sender, EventArgs e) { @@ -530,8 +525,7 @@ private void mainMenuBoxDump(object sender, EventArgs e) } else return; - string result; - SAV.dumpBoxes(path, out result, separate); + SAV.dumpBoxes(path, out string result, separate); WinFormsUtil.Alert(result); } private void mainMenuBoxDumpSingle(object sender, EventArgs e) @@ -541,8 +535,7 @@ private void mainMenuBoxDumpSingle(object sender, EventArgs e) if (fbd.ShowDialog() != DialogResult.OK) return; - string result; - SAV.dumpBox(fbd.SelectedPath, out result, CB_BoxSelect.SelectedIndex); + SAV.dumpBox(fbd.SelectedPath, out string result, CB_BoxSelect.SelectedIndex); WinFormsUtil.Alert(result); } private void manMenuBatchEditor(object sender, EventArgs e) @@ -1617,8 +1610,7 @@ public void populateFields(PKM pk, bool focus = true) if (pkm.Format != SAV.Generation) // past gen format { - string c; - pkm = PKMConverter.convertToFormat(pkm, SAV.PKMType, out c); + pkm = PKMConverter.convertToFormat(pkm, SAV.PKMType, out string _); if (pk.Format != pkm.Format && focus) // converted WinFormsUtil.Alert("Converted File."); } @@ -1790,7 +1782,7 @@ private void clickQR(object sender, EventArgs e) if (!pk.Valid || pk.Species <= 0) { WinFormsUtil.Alert("Invalid data detected."); return; } - string c; PKM pkz = PKMConverter.convertToFormat(pk, SAV.PKMType, out c); + PKM pkz = PKMConverter.convertToFormat(pk, SAV.PKMType, out string c); if (pkz == null) { WinFormsUtil.Alert(c); return; } @@ -2256,9 +2248,8 @@ private void updateIVs(object sender, EventArgs e) } private void updateEVs(object sender, EventArgs e) { - if (sender is MaskedTextBox) + if (sender is MaskedTextBox m) { - MaskedTextBox m = (MaskedTextBox)sender; if (Util.ToInt32(m.Text) > SAV.MaxEV) { m.Text = SAV.MaxEV.ToString(); return; } // recursive on text set } @@ -3436,9 +3427,8 @@ private void clickBoxDouble(object sender, MouseEventArgs e) return; if (ModifierKeys != Keys.Shift) { - var z = Application.OpenForms.Cast().FirstOrDefault(form => form.GetType() == typeof(SAV_BoxViewer)) as SAV_BoxViewer; - if (z != null) - { WinFormsUtil.CenterToForm(z, this); z.BringToFront(); return; } + if (getFirstFormOfType() is SAV_BoxViewer z) + { z.CenterToForm(this); z.BringToFront(); return; } } new SAV_BoxViewer(this).Show(); } @@ -4009,11 +3999,10 @@ private void loadBoxesFromDB(string path) if (dr == DialogResult.Cancel) return; - string result; bool clearAll = dr == DialogResult.Yes; bool? noSetb = getPKMSetOverride(); - SAV.loadBoxes(path, out result, CB_BoxSelect.SelectedIndex, clearAll, noSetb); + SAV.loadBoxes(path, out string result, CB_BoxSelect.SelectedIndex, clearAll, noSetb); setPKXBoxes(); WinFormsUtil.Alert(result); } @@ -4255,12 +4244,11 @@ private void B_JPEG_Click(object sender, EventArgs e) // Save Folder Related private void clickSaveFileName(object sender, EventArgs e) { - string path; string cgse = ""; string pathCache = CyberGadgetUtil.GetCacheFolder(); if (Directory.Exists(pathCache)) cgse = Path.Combine(pathCache); - if (!PathUtilWindows.detectSaveFile(out path, cgse)) + if (!PathUtilWindows.detectSaveFile(out string path, cgse)) WinFormsUtil.Error(path); if (path == null || !File.Exists(path)) return; if (WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Open save file from the following location?", path) == DialogResult.Yes) @@ -4424,9 +4412,8 @@ private void pbBoxSlot_DragDrop(object sender, DragEventArgs e) byte[] data = File.ReadAllBytes(file); MysteryGift mg = MysteryGift.getMysteryGift(data, fi.Extension); PKM temp = mg?.convertToPKM(SAV) ?? PKMConverter.getPKMfromBytes(data, prefer: fi.Extension.Length > 0 ? (fi.Extension.Last() - 0x30)&7 : SAV.Generation); - string c; - PKM pk = PKMConverter.convertToFormat(temp, SAV.PKMType, out c); + PKM pk = PKMConverter.convertToFormat(temp, SAV.PKMType, out string c); if (pk == null) { WinFormsUtil.Error(c); Console.WriteLine(c); return; } diff --git a/PKHeX.WinForms/Subforms/SAV_Database.cs b/PKHeX.WinForms/Subforms/SAV_Database.cs index 0123e1208..dd2575ef8 100644 --- a/PKHeX.WinForms/Subforms/SAV_Database.cs +++ b/PKHeX.WinForms/Subforms/SAV_Database.cs @@ -120,7 +120,7 @@ public SAV_Database(Main f1) private readonly string Counter; private readonly string Viewed; private const int MAXFORMAT = 7; - private readonly Func hash = pk => + private static string hash(PKM pk) { switch (pk.Format) { @@ -128,7 +128,7 @@ public SAV_Database(Main f1) case 2: return pk.Species.ToString("000") + ((PK2)pk).DV16.ToString("X4"); default: return pk.Species.ToString("000") + pk.PID.ToString("X8") + string.Join(" ", pk.IVs) + pk.AltForm.ToString("00"); } - }; + } // Important Events private void clickView(object sender, EventArgs e) @@ -517,7 +517,7 @@ private void B_Search_Click(object sender, EventArgs e) } if (Menu_SearchClones.Checked) - res = res.GroupBy(pk => hash(pk)).Where(group => group.Count() > 1).SelectMany(z => z); + res = res.GroupBy(hash).Where(group => group.Count() > 1).SelectMany(z => z); var results = res.ToArray(); if (results.Length == 0) @@ -637,7 +637,7 @@ private void Menu_DeleteClones_Click(object sender, EventArgs e) var deleted = 0; var db = RawDB.Where(pk => pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)) .OrderByDescending(file => new FileInfo(file.Identifier).LastWriteTime); - var clones = db.GroupBy(pk => hash(pk)).Where(group => group.Count() > 1).SelectMany(z => z.Skip(1)); + var clones = db.GroupBy(hash).Where(group => group.Count() > 1).SelectMany(z => z.Skip(1)); foreach (var pk in clones) { try { File.Delete(pk.Identifier); ++deleted; } diff --git a/PKHeX.WinForms/Subforms/Save Editors/Gen5/CGearBackground.cs b/PKHeX.WinForms/Subforms/Save Editors/Gen5/CGearBackground.cs index 5c5688fbd..f1c2d841b 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/Gen5/CGearBackground.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/Gen5/CGearBackground.cs @@ -197,13 +197,14 @@ public void SetImage(Bitmap img) Tiles = tilelist.ToArray(); } - private class Tile + private class Tile : IDisposable { public const int SIZE_TILE = 0x20; private const int TileWidth = 8; private const int TileHeight = 8; public readonly int[] ColorChoices; private Bitmap img; + public void Dispose() => img.Dispose(); public Tile(byte[] data = null) { @@ -297,6 +298,7 @@ public TileMap(byte[] data) } public byte[] Write() { + byte[] result; using (MemoryStream ms = new MemoryStream()) using (BinaryWriter bw = new BinaryWriter(ms)) { @@ -305,8 +307,9 @@ public byte[] Write() bw.Write((byte)TileChoices[i]); bw.Write((byte)Rotations[i]); } - return ms.ToArray(); + result = ms.ToArray(); } + return result; } } diff --git a/PKHeX.WinForms/Util/WinFormsUtil.cs b/PKHeX.WinForms/Util/WinFormsUtil.cs index c10f19a90..cb4024661 100644 --- a/PKHeX.WinForms/Util/WinFormsUtil.cs +++ b/PKHeX.WinForms/Util/WinFormsUtil.cs @@ -111,7 +111,7 @@ private static List FindContextMenuStrips(IEnumerable } return cs; } - internal static void CenterToForm(Control child, Control parent) + internal static void CenterToForm(this Control child, Control parent) { int x = parent.Location.X + (parent.Width - child.Width) / 2; int y = parent.Location.Y + (parent.Height - child.Height) / 2; diff --git a/Tests/PKHeX.Tests/PKM/PKMTests.cs b/Tests/PKHeX.Tests/PKM/PKMTests.cs index 01d0b81b5..09cba4235 100644 --- a/Tests/PKHeX.Tests/PKM/PKMTests.cs +++ b/Tests/PKHeX.Tests/PKM/PKMTests.cs @@ -246,14 +246,14 @@ public void PIDIVMatchingTest() }; var a_pkRS = MethodFinder.Analyze(pkRS); Assert.AreEqual(PIDType.BACD_R_S, a_pkRS?.Type, "Unable to match PID to BACD-R shiny spread"); - Assert.AreEqual(true, 0x0020 == a_pkRS?.OriginSeed, "Unable to match PID to BACD-R shiny spread origin seed"); + Assert.IsTrue(0x0020 == a_pkRS?.OriginSeed, "Unable to match PID to BACD-R shiny spread origin seed"); var pkPS0 = new PK3 {PID = 0x7B2D9DA7}; // Zubat (Cave) - Assert.AreEqual(true, MethodFinder.getPokeSpotSeeds(pkPS0, 0).Any(), "PokeSpot encounter info mismatch (Common)"); + Assert.IsTrue(MethodFinder.getPokeSpotSeeds(pkPS0, 0).Any(), "PokeSpot encounter info mismatch (Common)"); var pkPS1 = new PK3 {PID = 0x3EE9AF66}; // Gligar (Rock) - Assert.AreEqual(true, MethodFinder.getPokeSpotSeeds(pkPS1, 1).Any(), "PokeSpot encounter info mismatch (Uncommon)"); + Assert.IsTrue(MethodFinder.getPokeSpotSeeds(pkPS1, 1).Any(), "PokeSpot encounter info mismatch (Uncommon)"); var pkPS2 = new PK3 {PID = 0x9B667F3C}; // Surskit (Oasis) - Assert.AreEqual(true, MethodFinder.getPokeSpotSeeds(pkPS2, 2).Any(), "PokeSpot encounter info mismatch (Rare)"); + Assert.IsTrue(MethodFinder.getPokeSpotSeeds(pkPS2, 2).Any(), "PokeSpot encounter info mismatch (Rare)"); var pk1U = new PK3 {