Fix CA1854

This commit is contained in:
RoosterDragon
2023-03-12 17:38:38 +00:00
committed by abcdefg30
parent 56fe08cb00
commit 231bf01f18
26 changed files with 93 additions and 86 deletions

View File

@@ -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<T>.Clear() instead of Span<T>.Fill().
dotnet_diagnostic.CA1855.severity = warning

View File

@@ -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<float>("VolumeModifier", nd["VolumeModifier"].Value);
if (nd.TryGetValue("VolumeModifier", out yaml))
VolumeModifier = FieldLoader.GetValue<float>("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)

View File

@@ -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);
}
}

View File

@@ -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))

View File

@@ -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)

View File

@@ -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<Hotkey> GetHotkeyReference(string name)
{
// Is this a mod-defined hotkey?

View File

@@ -157,25 +157,25 @@ namespace OpenRA
// Allow inherited mods to import parent maps.
var compat = new List<string> { 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<string[]>("PackageFormats", yaml["PackageFormats"].Value);
if (yaml.TryGetValue("PackageFormats", out entry))
PackageFormats = FieldLoader.GetValue<string[]>("PackageFormats", entry.Value);
if (yaml.ContainsKey("SoundFormats"))
SoundFormats = FieldLoader.GetValue<string[]>("SoundFormats", yaml["SoundFormats"].Value);
if (yaml.TryGetValue("SoundFormats", out entry))
SoundFormats = FieldLoader.GetValue<string[]>("SoundFormats", entry.Value);
if (yaml.ContainsKey("SpriteFormats"))
SpriteFormats = FieldLoader.GetValue<string[]>("SpriteFormats", yaml["SpriteFormats"].Value);
if (yaml.TryGetValue("SpriteFormats", out entry))
SpriteFormats = FieldLoader.GetValue<string[]>("SpriteFormats", entry.Value);
if (yaml.ContainsKey("VideoFormats"))
VideoFormats = FieldLoader.GetValue<string[]>("VideoFormats", yaml["VideoFormats"].Value);
if (yaml.TryGetValue("VideoFormats", out entry))
VideoFormats = FieldLoader.GetValue<string[]>("VideoFormats", entry.Value);
}
public void LoadCustomData(ObjectCreator oc)

View File

@@ -146,7 +146,7 @@ namespace OpenRA
public static List<MiniYamlNode> NodesOrEmpty(MiniYaml y, string s)
{
var nd = y.ToDictionary();
return nd.ContainsKey(s) ? nd[s].Nodes : new List<MiniYamlNode>();
return nd.TryGetValue(s, out var v) ? v.Nodes : new List<MiniYamlNode>();
}
static List<MiniYamlNode> FromLines(IEnumerable<ReadOnlyMemory<char>> lines, string filename, bool discardCommentsAndWhitespace, Dictionary<string, string> 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))

View File

@@ -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()
{

View File

@@ -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();

View File

@@ -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<string, int>((Dictionary<string, int>)args["substitutions"]) :
var substitutions = args.TryGetValue("substitutions", out var subs) ?
new Dictionary<string, int>((Dictionary<string, int>)subs) :
new Dictionary<string, int>();
substitutions.Add("WINDOW_RIGHT", Game.Renderer.Resolution.Width);

View File

@@ -370,11 +370,11 @@ namespace OpenRA.Mods.Cnc.UtilityCommands
var visibility = FieldLoader.GetValue<int>(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<float>(kv.Key, kv.Value.Replace(',', '.'));
lightingNodes.Add(new MiniYamlNode(lightingTypes[kv.Key], FieldSaver.FormatValue(value)));
lightingNodes.Add(new MiniYamlNode(lightingType, FieldSaver.FormatValue(value)));
}
}

View File

@@ -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)

View File

@@ -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;

View File

@@ -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);

View File

@@ -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<Size>("FrameSize", png.EmbeddedData["FrameSize"]);
frameSize = FieldLoader.GetValue<Size>("FrameSize", value);
// ... either use FrameAmount or calculate how many times FrameSize fits into the image.
if (png.EmbeddedData.ContainsKey("FrameAmount"))
frameAmount = FieldLoader.GetValue<int>("FrameAmount", png.EmbeddedData["FrameAmount"]);
if (png.EmbeddedData.TryGetValue("FrameAmount", out value))
frameAmount = FieldLoader.GetValue<int>("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<int>("FrameAmount", png.EmbeddedData["FrameAmount"]);
frameAmount = FieldLoader.GetValue<int>("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<float2>("Offset", png.EmbeddedData["Offset"]);
if (png.EmbeddedData.TryGetValue("Offset", out value))
offset = FieldLoader.GetValue<float2>("Offset", value);
else
offset = float2.Zero;

View File

@@ -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

View File

@@ -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);

View File

@@ -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));

View File

@@ -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<SupportPowerInstance>();

View File

@@ -91,8 +91,8 @@ namespace OpenRA.Mods.Common.Traits
if (speed > 0)
{
var nodesDict = t.Value.ToDictionary();
var cost = nodesDict.ContainsKey("PathingCost")
? FieldLoader.GetValue<short>("cost", nodesDict["PathingCost"].Value)
var cost = nodesDict.TryGetValue("PathingCost", out var entry)
? FieldLoader.GetValue<short>("cost", entry.Value)
: 10000 / speed;
ret.Add(t.Key, new TerrainInfo(speed, (short)cost));
}

View File

@@ -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;

View File

@@ -46,8 +46,8 @@ namespace OpenRA.Mods.Common.Widgets
this.world = world;
var highlightOnButtonPress = false;
if (logicArgs.ContainsKey("HighlightOnButtonPress"))
highlightOnButtonPress = FieldLoader.GetValue<bool>("HighlightOnButtonPress", logicArgs["HighlightOnButtonPress"].Value);
if (logicArgs.TryGetValue("HighlightOnButtonPress", out var entry))
highlightOnButtonPress = FieldLoader.GetValue<bool>("HighlightOnButtonPress", entry.Value);
var attackMoveButton = widget.GetOrNull<ButtonWidget>("ATTACK_MOVE");
if (attackMoveButton != null)

View File

@@ -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);
}

View File

@@ -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;
}

View File

@@ -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