From 231bf01f1874d15cc773dc804400a1e2dcb356c5 Mon Sep 17 00:00:00 2001 From: RoosterDragon Date: Sun, 12 Mar 2023 17:38:38 +0000 Subject: [PATCH] Fix CA1854 --- .editorconfig | 3 +++ OpenRA.Game/GameRules/MusicInfo.cs | 12 +++++----- OpenRA.Game/Graphics/CursorSequence.cs | 19 ++++++++------- OpenRA.Game/Graphics/HardwarePalette.cs | 3 +++ OpenRA.Game/Graphics/WorldRenderer.cs | 4 ++-- OpenRA.Game/HotkeyManager.cs | 5 +++- OpenRA.Game/Manifest.cs | 24 +++++++++---------- OpenRA.Game/MiniYaml.cs | 6 ++--- OpenRA.Game/Sound/Sound.cs | 12 +++++----- OpenRA.Game/Sync.cs | 4 ++-- OpenRA.Game/Widgets/Widget.cs | 4 ++-- .../UtilityCommands/ImportGen2MapCommand.cs | 4 ++-- .../LoadScreens/LogoStripeLoadScreen.cs | 4 ++-- .../LoadScreens/SheetLoadScreen.cs | 13 +++++----- .../Properties/ProductionProperties.cs | 4 ++-- .../SpriteLoaders/PngSheetLoader.cs | 16 ++++++------- .../BotModuleLogic/BaseBuilderQueueManager.cs | 6 ++--- .../BotModules/SupportPowerBotModule.cs | 3 +-- .../Traits/BotModules/UnitBuilderBotModule.cs | 8 +++---- .../SupportPowers/SupportPowerManager.cs | 4 ++-- OpenRA.Mods.Common/Traits/World/Locomotor.cs | 4 ++-- .../Traits/World/SmudgeLayer.cs | 4 ++-- .../Widgets/Logic/Ingame/CommandBarLogic.cs | 4 ++-- .../Installation/InstallFromSourceLogic.cs | 2 +- .../Widgets/Logic/MapChooserLogic.cs | 4 ++-- .../UtilityCommands/D2kMapImporter.cs | 3 +-- 26 files changed, 93 insertions(+), 86 deletions(-) diff --git a/.editorconfig b/.editorconfig index d32351ab37..f53d1af2ae 100644 --- a/.editorconfig +++ b/.editorconfig @@ -788,6 +788,9 @@ dotnet_diagnostic.CA1852.severity = warning # Unnecessary call to 'Dictionary.ContainsKey(key)'. dotnet_diagnostic.CA1853.severity = warning +# Prefer the IDictionary.TryGetValue(TKey, out TValue) method. +dotnet_diagnostic.CA1854.severity = warning + # Use Span.Clear() instead of Span.Fill(). dotnet_diagnostic.CA1855.severity = warning diff --git a/OpenRA.Game/GameRules/MusicInfo.cs b/OpenRA.Game/GameRules/MusicInfo.cs index debd8b9805..f4233a2bed 100644 --- a/OpenRA.Game/GameRules/MusicInfo.cs +++ b/OpenRA.Game/GameRules/MusicInfo.cs @@ -28,14 +28,14 @@ namespace OpenRA.GameRules Title = value.Value; var nd = value.ToDictionary(); - if (nd.ContainsKey("Hidden")) - bool.TryParse(nd["Hidden"].Value, out Hidden); + if (nd.TryGetValue("Hidden", out var yaml)) + bool.TryParse(yaml.Value, out Hidden); - if (nd.ContainsKey("VolumeModifier")) - VolumeModifier = FieldLoader.GetValue("VolumeModifier", nd["VolumeModifier"].Value); + if (nd.TryGetValue("VolumeModifier", out yaml)) + VolumeModifier = FieldLoader.GetValue("VolumeModifier", yaml.Value); - var ext = nd.ContainsKey("Extension") ? nd["Extension"].Value : "aud"; - Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key) + "." + ext; + var ext = nd.TryGetValue("Extension", out yaml) ? yaml.Value : "aud"; + Filename = (nd.TryGetValue("Filename", out yaml) ? yaml.Value : key) + "." + ext; } public void Load(IReadOnlyFileSystem fileSystem) diff --git a/OpenRA.Game/Graphics/CursorSequence.cs b/OpenRA.Game/Graphics/CursorSequence.cs index fe7f004602..2eb2fb9961 100644 --- a/OpenRA.Game/Graphics/CursorSequence.cs +++ b/OpenRA.Game/Graphics/CursorSequence.cs @@ -34,12 +34,13 @@ namespace OpenRA.Graphics var cursorSprites = cache[cursorSrc]; Frames = cursorSprites.Skip(Start).ToArray(); - if ((d.ContainsKey("Length") && d["Length"].Value == "*") || (d.ContainsKey("End") && d["End"].Value == "*")) + if ((d.TryGetValue("Length", out var yaml) && yaml.Value == "*") || + (d.TryGetValue("End", out yaml) && yaml.Value == "*")) Length = Frames.Length; - else if (d.ContainsKey("Length")) - Length = Exts.ParseIntegerInvariant(d["Length"].Value); - else if (d.ContainsKey("End")) - Length = Exts.ParseIntegerInvariant(d["End"].Value) - Start; + else if (d.TryGetValue("Length", out yaml)) + Length = Exts.ParseIntegerInvariant(yaml.Value); + else if (d.TryGetValue("End", out yaml)) + Length = Exts.ParseIntegerInvariant(yaml.Value) - Start; else Length = 1; @@ -51,15 +52,15 @@ namespace OpenRA.Graphics if (Length > cursorSprites.Length) throw new YamlException($"Cursor {name}: {nameof(Length)} is greater than the length of the sprite sequence."); - if (d.ContainsKey("X")) + if (d.TryGetValue("X", out yaml)) { - Exts.TryParseIntegerInvariant(d["X"].Value, out var x); + Exts.TryParseIntegerInvariant(yaml.Value, out var x); Hotspot = Hotspot.WithX(x); } - if (d.ContainsKey("Y")) + if (d.TryGetValue("Y", out yaml)) { - Exts.TryParseIntegerInvariant(d["Y"].Value, out var y); + Exts.TryParseIntegerInvariant(yaml.Value, out var y); Hotspot = Hotspot.WithY(y); } } diff --git a/OpenRA.Game/Graphics/HardwarePalette.cs b/OpenRA.Game/Graphics/HardwarePalette.cs index b168258a19..f8e67bc234 100644 --- a/OpenRA.Game/Graphics/HardwarePalette.cs +++ b/OpenRA.Game/Graphics/HardwarePalette.cs @@ -79,6 +79,9 @@ namespace OpenRA.Graphics CopyPaletteToBuffer(index, p); } + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Performance", "CA1854:Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method", + Justification = "False positive - indexer is a set not a get.")] public void ReplacePalette(string name, IPalette p) { if (mutablePalettes.ContainsKey(name)) diff --git a/OpenRA.Game/Graphics/WorldRenderer.cs b/OpenRA.Game/Graphics/WorldRenderer.cs index 53bd2b75e2..6d3e514216 100644 --- a/OpenRA.Game/Graphics/WorldRenderer.cs +++ b/OpenRA.Game/Graphics/WorldRenderer.cs @@ -109,8 +109,8 @@ namespace OpenRA.Graphics palette.ReplacePalette(name, pal); // Update cached PlayerReference if one exists - if (palettes.ContainsKey(name)) - palettes[name].Palette = pal; + if (palettes.TryGetValue(name, out var paletteReference)) + paletteReference.Palette = pal; } public void SetPaletteColorShift(string name, float hueOffset, float satOffset, float valueModifier, float minHue, float maxHue) diff --git a/OpenRA.Game/HotkeyManager.cs b/OpenRA.Game/HotkeyManager.cs index 70ca85a545..a28f9266a3 100644 --- a/OpenRA.Game/HotkeyManager.cs +++ b/OpenRA.Game/HotkeyManager.cs @@ -35,7 +35,7 @@ namespace OpenRA foreach (var kv in settings) { - if (definitions.ContainsKey(kv.Key) && !definitions[kv.Key].Readonly) + if (definitions.TryGetValue(kv.Key, out var definition) && !definition.Readonly) keys[kv.Key] = kv.Value; } @@ -43,6 +43,9 @@ namespace OpenRA hd.Value.HasDuplicates = GetFirstDuplicate(hd.Value, this[hd.Value.Name].GetValue()) != null; } + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Performance", "CA1854:Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method", + Justification = "Func must perform a live lookup in the collection, as the lookup value can change.")] internal Func GetHotkeyReference(string name) { // Is this a mod-defined hotkey? diff --git a/OpenRA.Game/Manifest.cs b/OpenRA.Game/Manifest.cs index d9739f7585..4405cfc684 100644 --- a/OpenRA.Game/Manifest.cs +++ b/OpenRA.Game/Manifest.cs @@ -157,25 +157,25 @@ namespace OpenRA // Allow inherited mods to import parent maps. var compat = new List { Id }; - if (yaml.ContainsKey("SupportsMapsFrom")) - compat.AddRange(yaml["SupportsMapsFrom"].Value.Split(',').Select(c => c.Trim())); + if (yaml.TryGetValue("SupportsMapsFrom", out var entry)) + compat.AddRange(entry.Value.Split(',').Select(c => c.Trim())); MapCompatibility = compat.ToArray(); - if (yaml.ContainsKey("DefaultOrderGenerator")) - DefaultOrderGenerator = yaml["DefaultOrderGenerator"].Value; + if (yaml.TryGetValue("DefaultOrderGenerator", out entry)) + DefaultOrderGenerator = entry.Value; - if (yaml.ContainsKey("PackageFormats")) - PackageFormats = FieldLoader.GetValue("PackageFormats", yaml["PackageFormats"].Value); + if (yaml.TryGetValue("PackageFormats", out entry)) + PackageFormats = FieldLoader.GetValue("PackageFormats", entry.Value); - if (yaml.ContainsKey("SoundFormats")) - SoundFormats = FieldLoader.GetValue("SoundFormats", yaml["SoundFormats"].Value); + if (yaml.TryGetValue("SoundFormats", out entry)) + SoundFormats = FieldLoader.GetValue("SoundFormats", entry.Value); - if (yaml.ContainsKey("SpriteFormats")) - SpriteFormats = FieldLoader.GetValue("SpriteFormats", yaml["SpriteFormats"].Value); + if (yaml.TryGetValue("SpriteFormats", out entry)) + SpriteFormats = FieldLoader.GetValue("SpriteFormats", entry.Value); - if (yaml.ContainsKey("VideoFormats")) - VideoFormats = FieldLoader.GetValue("VideoFormats", yaml["VideoFormats"].Value); + if (yaml.TryGetValue("VideoFormats", out entry)) + VideoFormats = FieldLoader.GetValue("VideoFormats", entry.Value); } public void LoadCustomData(ObjectCreator oc) diff --git a/OpenRA.Game/MiniYaml.cs b/OpenRA.Game/MiniYaml.cs index 260f7003bd..2a9892a4b6 100644 --- a/OpenRA.Game/MiniYaml.cs +++ b/OpenRA.Game/MiniYaml.cs @@ -146,7 +146,7 @@ namespace OpenRA public static List NodesOrEmpty(MiniYaml y, string s) { var nd = y.ToDictionary(); - return nd.ContainsKey(s) ? nd[s].Nodes : new List(); + return nd.TryGetValue(s, out var v) ? v.Nodes : new List(); } static List FromLines(IEnumerable> lines, string filename, bool discardCommentsAndWhitespace, Dictionary stringPool) @@ -368,8 +368,8 @@ namespace OpenRA throw new YamlException( $"{n.Location}: Parent type `{n.Value.Value}` not found"); - if (inherited.ContainsKey(n.Value.Value)) - throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {inherited[n.Value.Value]} (note: may be from a derived tree)"); + if (inherited.TryGetValue(n.Value.Value, out var location)) + throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {location} (note: may be from a derived tree)"); inherited.Add(n.Value.Value, n.Location); foreach (var r in ResolveInherits(parent, tree, inherited)) diff --git a/OpenRA.Game/Sound/Sound.cs b/OpenRA.Game/Sound/Sound.cs index 2d050840ad..f4ad227bff 100644 --- a/OpenRA.Game/Sound/Sound.cs +++ b/OpenRA.Game/Sound/Sound.cs @@ -356,7 +356,7 @@ namespace OpenRA public float VideoSeekPosition => video?.SeekPosition ?? 0; // Returns true if played successfully - public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player p, Actor voicedActor, string type, string definition, string variant, + public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player player, Actor voicedActor, string type, string definition, string variant, bool relative, WPos pos, float volumeModifier, bool attenuateVolume) { if (ruleset == null) @@ -399,16 +399,16 @@ namespace OpenRA if (variant != null) { - if (rules.Variants.ContainsKey(variant) && !rules.DisableVariants.Contains(definition)) - suffix = rules.Variants[variant][id % rules.Variants[variant].Length]; - if (rules.Prefixes.ContainsKey(variant) && !rules.DisablePrefixes.Contains(definition)) - prefix = rules.Prefixes[variant][id % rules.Prefixes[variant].Length]; + if (rules.Variants.TryGetValue(variant, out var v) && !rules.DisableVariants.Contains(definition)) + suffix = v[id % v.Length]; + if (rules.Prefixes.TryGetValue(variant, out var p) && !rules.DisablePrefixes.Contains(definition)) + prefix = p[id % p.Length]; } var name = prefix + clip + suffix; var actorId = voicedActor != null && voicedActor.World.Selection.Contains(voicedActor) ? 0 : id; - if (!string.IsNullOrEmpty(name) && (p == null || p == p.World.LocalPlayer)) + if (!string.IsNullOrEmpty(name) && (player == null || player == player.World.LocalPlayer)) { ISound PlaySound() { diff --git a/OpenRA.Game/Sync.cs b/OpenRA.Game/Sync.cs index 4d9dd8bd6f..06e2e9b5fd 100644 --- a/OpenRA.Game/Sync.cs +++ b/OpenRA.Game/Sync.cs @@ -57,8 +57,8 @@ namespace OpenRA static void EmitSyncOpcodes(Type type, ILGenerator il) { - if (CustomHashFunctions.ContainsKey(type)) - il.EmitCall(OpCodes.Call, CustomHashFunctions[type], null); + if (CustomHashFunctions.TryGetValue(type, out var hashFunction)) + il.EmitCall(OpCodes.Call, hashFunction, null); else if (type == typeof(bool)) { var l = il.DefineLabel(); diff --git a/OpenRA.Game/Widgets/Widget.cs b/OpenRA.Game/Widgets/Widget.cs index 6c0472e510..3ab1975e8a 100644 --- a/OpenRA.Game/Widgets/Widget.cs +++ b/OpenRA.Game/Widgets/Widget.cs @@ -264,8 +264,8 @@ namespace OpenRA.Widgets ? new Rectangle(0, 0, Game.Renderer.Resolution.Width, Game.Renderer.Resolution.Height) : Parent.Bounds; - var substitutions = args.ContainsKey("substitutions") ? - new Dictionary((Dictionary)args["substitutions"]) : + var substitutions = args.TryGetValue("substitutions", out var subs) ? + new Dictionary((Dictionary)subs) : new Dictionary(); substitutions.Add("WINDOW_RIGHT", Game.Renderer.Resolution.Width); diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportGen2MapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportGen2MapCommand.cs index 8bef579550..2f99bdf82f 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportGen2MapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportGen2MapCommand.cs @@ -370,11 +370,11 @@ namespace OpenRA.Mods.Cnc.UtilityCommands var visibility = FieldLoader.GetValue(kv.Key, kv.Value); lightingNodes.Add(new MiniYamlNode("Range", FieldSaver.FormatValue(new WDist(visibility * 4)))); } - else if (lightingTypes.ContainsKey(kv.Key)) + else if (lightingTypes.TryGetValue(kv.Key, out var lightingType)) { // Some maps use "," instead of "."! var value = FieldLoader.GetValue(kv.Key, kv.Value.Replace(',', '.')); - lightingNodes.Add(new MiniYamlNode(lightingTypes[kv.Key], FieldSaver.FormatValue(value))); + lightingNodes.Add(new MiniYamlNode(lightingType, FieldSaver.FormatValue(value))); } } diff --git a/OpenRA.Mods.Common/LoadScreens/LogoStripeLoadScreen.cs b/OpenRA.Mods.Common/LoadScreens/LogoStripeLoadScreen.cs index 87c3968daa..1bcf46b933 100644 --- a/OpenRA.Mods.Common/LoadScreens/LogoStripeLoadScreen.cs +++ b/OpenRA.Mods.Common/LoadScreens/LogoStripeLoadScreen.cs @@ -32,8 +32,8 @@ namespace OpenRA.Mods.Common.LoadScreens { base.Init(modData, info); - if (info.ContainsKey("Text")) - messages = info["Text"].Split(','); + if (info.TryGetValue("Text", out var text)) + messages = text.Split(','); } public override void DisplayInner(Renderer r, Sheet s, int density) diff --git a/OpenRA.Mods.Common/LoadScreens/SheetLoadScreen.cs b/OpenRA.Mods.Common/LoadScreens/SheetLoadScreen.cs index 7f5df3fb6a..e80465b949 100644 --- a/OpenRA.Mods.Common/LoadScreens/SheetLoadScreen.cs +++ b/OpenRA.Mods.Common/LoadScreens/SheetLoadScreen.cs @@ -56,22 +56,21 @@ namespace OpenRA.Mods.Common.LoadScreens sheet = null; } - if (sheet == null && Info.ContainsKey("Image")) + if (sheet == null && Info.TryGetValue("Image", out var image)) { - var key = "Image"; density = 1; - if (dpiScale > 2 && Info.ContainsKey("Image3x")) + if (dpiScale > 2 && Info.TryGetValue("Image3x", out var image3)) { - key = "Image3x"; + image = image3; density = 3; } - else if (dpiScale > 1 && Info.ContainsKey("Image2x")) + else if (dpiScale > 1 && Info.TryGetValue("Image2x", out var image2)) { - key = "Image2x"; + image = image2; density = 2; } - using (var stream = ModData.DefaultFileSystem.Open(Platform.ResolvePath(Info[key]))) + using (var stream = ModData.DefaultFileSystem.Open(Platform.ResolvePath(image))) { sheet = new Sheet(SheetType.BGRA, stream); sheet.GetTexture().ScaleFilter = TextureScaleFilter.Linear; diff --git a/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs index 3547fcaf9d..403d12ffe0 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs @@ -225,8 +225,8 @@ namespace OpenRA.Mods.Common.Scripting var queue = GetBuildableInfo(unit.Info.Name).Queue.First(); - if (productionHandlers.ContainsKey(queue)) - productionHandlers[queue](factory, unit); + if (productionHandlers.TryGetValue(queue, out var productionHandler)) + productionHandler(factory, unit); } var triggers = TriggerGlobal.GetScriptTriggers(player.PlayerActor); diff --git a/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs b/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs index 7363dd786d..f52bbb26a5 100644 --- a/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs +++ b/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs @@ -115,29 +115,29 @@ namespace OpenRA.Mods.Common.SpriteLoaders var frameSize = new Size(png.Width, png.Height); var frameAmount = 1; - if (png.EmbeddedData.ContainsKey("FrameSize")) + if (png.EmbeddedData.TryGetValue("FrameSize", out var value)) { // If FrameSize exist, use it and... - frameSize = FieldLoader.GetValue("FrameSize", png.EmbeddedData["FrameSize"]); + frameSize = FieldLoader.GetValue("FrameSize", value); // ... either use FrameAmount or calculate how many times FrameSize fits into the image. - if (png.EmbeddedData.ContainsKey("FrameAmount")) - frameAmount = FieldLoader.GetValue("FrameAmount", png.EmbeddedData["FrameAmount"]); + if (png.EmbeddedData.TryGetValue("FrameAmount", out value)) + frameAmount = FieldLoader.GetValue("FrameAmount", value); else frameAmount = png.Width / frameSize.Width * (png.Height / frameSize.Height); } - else if (png.EmbeddedData.ContainsKey("FrameAmount")) + else if (png.EmbeddedData.TryGetValue("FrameAmount", out value)) { // Otherwise, calculate the number of frames by splitting the image horizontally by FrameAmount. - frameAmount = FieldLoader.GetValue("FrameAmount", png.EmbeddedData["FrameAmount"]); + frameAmount = FieldLoader.GetValue("FrameAmount", value); frameSize = new Size(png.Width / frameAmount, png.Height); } float2 offset; // If Offset property exists, use its value. Otherwise assume the frame is centered. - if (png.EmbeddedData.ContainsKey("Offset")) - offset = FieldLoader.GetValue("Offset", png.EmbeddedData["Offset"]); + if (png.EmbeddedData.TryGetValue("Offset", out value)) + offset = FieldLoader.GetValue("Offset", value); else offset = float2.Zero; diff --git a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs index f96d666a63..f9a212aca2 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs @@ -322,8 +322,8 @@ namespace OpenRA.Mods.Common.Traits // Does this building have initial delay, if so have we passed it? if (baseBuilder.Info.BuildingDelays != null && - baseBuilder.Info.BuildingDelays.ContainsKey(name) && - baseBuilder.Info.BuildingDelays[name] > world.WorldTick) + baseBuilder.Info.BuildingDelays.TryGetValue(name, out var delay) && + delay > world.WorldTick) continue; // Can we build this structure? @@ -341,7 +341,7 @@ namespace OpenRA.Mods.Common.Traits if (count * 100 > frac.Value * playerBuildings.Length) continue; - if (baseBuilder.Info.BuildingLimits.ContainsKey(name) && baseBuilder.Info.BuildingLimits[name] <= count) + if (baseBuilder.Info.BuildingLimits.TryGetValue(name, out var limit) && limit <= count) continue; // If we're considering to build a naval structure, check whether there is enough water inside the base perimeter diff --git a/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs index 0b8cccfcdd..f266945429 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/SupportPowerBotModule.cs @@ -79,9 +79,8 @@ namespace OpenRA.Mods.Common.Traits // If we have recently tried and failed to find a use location for a power, then do not try again until later var isDelayed = waitingPowers[sp] > 0; - if (sp.Ready && !isDelayed && powerDecisions.ContainsKey(sp.Info.OrderName)) + if (sp.Ready && !isDelayed && powerDecisions.TryGetValue(sp.Info.OrderName, out var powerDecision)) { - var powerDecision = powerDecisions[sp.Info.OrderName]; if (powerDecision == null) { AIUtils.BotDebug("{0} couldn't find powerDecision for {1}", player.PlayerName, sp.Info.OrderName); diff --git a/OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs index a7b7152152..19e25851da 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs @@ -121,13 +121,13 @@ namespace OpenRA.Mods.Common.Traits return; if (Info.UnitDelays != null && - Info.UnitDelays.ContainsKey(name) && - Info.UnitDelays[name] > world.WorldTick) + Info.UnitDelays.TryGetValue(name, out var delay) && + delay > world.WorldTick) return; if (Info.UnitLimits != null && - Info.UnitLimits.ContainsKey(name) && - world.Actors.Count(a => a.Owner == player && a.Info.Name == name) >= Info.UnitLimits[name]) + Info.UnitLimits.TryGetValue(name, out var limit) && + world.Actors.Count(a => a.Owner == player && a.Info.Name == name) >= limit) return; bot.QueueOrder(Order.StartProduction(queue.Actor, name, 1)); diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs b/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs index 8b101c5c35..09bed55e25 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/SupportPowerManager.cs @@ -102,8 +102,8 @@ namespace OpenRA.Mods.Common.Traits public void ResolveOrder(Actor self, Order order) { // order.OrderString is the key of the support power - if (Powers.ContainsKey(order.OrderString)) - Powers[order.OrderString].Activate(order); + if (Powers.TryGetValue(order.OrderString, out var sp)) + sp.Activate(order); } static readonly SupportPowerInstance[] NoInstances = Array.Empty(); diff --git a/OpenRA.Mods.Common/Traits/World/Locomotor.cs b/OpenRA.Mods.Common/Traits/World/Locomotor.cs index de5afaf2d6..a415eb9290 100644 --- a/OpenRA.Mods.Common/Traits/World/Locomotor.cs +++ b/OpenRA.Mods.Common/Traits/World/Locomotor.cs @@ -91,8 +91,8 @@ namespace OpenRA.Mods.Common.Traits if (speed > 0) { var nodesDict = t.Value.ToDictionary(); - var cost = nodesDict.ContainsKey("PathingCost") - ? FieldLoader.GetValue("cost", nodesDict["PathingCost"].Value) + var cost = nodesDict.TryGetValue("PathingCost", out var entry) + ? FieldLoader.GetValue("cost", entry.Value) : 10000 / speed; ret.Add(t.Key, new TerrainInfo(speed, (short)cost)); } diff --git a/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs b/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs index 49b430522f..9b830c6fe2 100644 --- a/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/SmudgeLayer.cs @@ -166,7 +166,7 @@ namespace OpenRA.Mods.Common.Traits { // Existing smudge; make it deeper // A null Sequence indicates a deleted smudge. - var tile = dirty.ContainsKey(loc) && dirty[loc].Sequence != null ? dirty[loc] : tiles[loc]; + var tile = dirty.TryGetValue(loc, out var d) && d.Sequence != null ? d : tiles[loc]; var maxDepth = smudges[tile.Type].Length; if (tile.Depth < maxDepth - 1) tile.Depth++; @@ -180,7 +180,7 @@ namespace OpenRA.Mods.Common.Traits if (!world.Map.Contains(loc)) return; - var tile = dirty.ContainsKey(loc) ? dirty[loc] : default; + var tile = dirty.TryGetValue(loc, out var d) ? d : default; // Setting Sequence to null to indicate a deleted smudge. tile.Sequence = null; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/CommandBarLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/CommandBarLogic.cs index f70dfe4b1f..6889540ac4 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/CommandBarLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/CommandBarLogic.cs @@ -46,8 +46,8 @@ namespace OpenRA.Mods.Common.Widgets this.world = world; var highlightOnButtonPress = false; - if (logicArgs.ContainsKey("HighlightOnButtonPress")) - highlightOnButtonPress = FieldLoader.GetValue("HighlightOnButtonPress", logicArgs["HighlightOnButtonPress"].Value); + if (logicArgs.TryGetValue("HighlightOnButtonPress", out var entry)) + highlightOnButtonPress = FieldLoader.GetValue("HighlightOnButtonPress", entry.Value); var attackMoveButton = widget.GetOrNull("ATTACK_MOVE"); if (attackMoveButton != null) diff --git a/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromSourceLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromSourceLogic.cs index 71b5f88a8b..80f100e2c3 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromSourceLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromSourceLogic.cs @@ -264,7 +264,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic foreach (var packageInstallationNode in modSource.Install.Where(x => x.Key == "ContentPackage")) { var packageName = packageInstallationNode.Value.Nodes.SingleOrDefault(x => x.Key == "Name")?.Value.Value; - if (!string.IsNullOrEmpty(packageName) && selectedPackages.ContainsKey(packageName) && selectedPackages[packageName]) + if (!string.IsNullOrEmpty(packageName) && selectedPackages.TryGetValue(packageName, out var required) && required) RunSourceActions(packageInstallationNode); } diff --git a/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs index ff5165d2c9..8c4135ba9d 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs @@ -189,9 +189,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic SetupMapTab(MapClassification.User, filter, "USER_MAPS_TAB_BUTTON", "USER_MAPS_TAB", itemTemplate); SetupMapTab(MapClassification.System, filter, "SYSTEM_MAPS_TAB_BUTTON", "SYSTEM_MAPS_TAB", itemTemplate); - if (initialMap == null && tabMaps.ContainsKey(initialTab) && tabMaps[initialTab].Length > 0) + if (initialMap == null && tabMaps.TryGetValue(initialTab, out var map) && map.Length > 0) { - selectedUid = Game.ModData.MapCache.ChooseInitialMap(tabMaps[initialTab].Select(mp => mp.Uid).First(), + selectedUid = Game.ModData.MapCache.ChooseInitialMap(map.Select(mp => mp.Uid).First(), Game.CosmeticRandom); currentTab = initialTab; } diff --git a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs index 36d6a1baad..810ea8bb20 100644 --- a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs +++ b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs @@ -367,9 +367,8 @@ namespace OpenRA.Mods.D2k.UtilityCommands map.Resources[locationOnMap] = new ResourceTile(1, 2); // Actors - if (ActorDataByActorCode.ContainsKey(tileSpecialInfo)) + if (ActorDataByActorCode.TryGetValue(tileSpecialInfo, out var kvp)) { - var kvp = ActorDataByActorCode[tileSpecialInfo]; if (!rules.Actors.ContainsKey(kvp.Actor.ToLowerInvariant())) Console.WriteLine($"Ignoring unknown actor type: `{kvp.Actor.ToLowerInvariant()}`"); else