Enable Net 7 and Net 8 style rules.

This commit is contained in:
RoosterDragon
2024-11-25 20:15:58 +00:00
committed by Gustas Kažukauskas
parent 71ae0aedfb
commit cfde11556f
31 changed files with 74 additions and 94 deletions

View File

@@ -748,7 +748,7 @@ dotnet_diagnostic.CA1305.severity = warning
dotnet_diagnostic.CA1310.severity = warning dotnet_diagnostic.CA1310.severity = warning
# Specify a culture or use an invariant version. # Specify a culture or use an invariant version.
dotnet_diagnostic.CA1311.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1311.severity = warning
### Portability and Interoperability Rules ### Portability and Interoperability Rules
### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/interoperability-warnings ### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/interoperability-warnings
@@ -763,19 +763,19 @@ dotnet_diagnostic.CA1417.severity = warning
dotnet_diagnostic.CA1507.severity = warning dotnet_diagnostic.CA1507.severity = warning
# Use ArgumentNullException throw helper. # Use ArgumentNullException throw helper.
dotnet_diagnostic.CA1510.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1510.severity = warning
# Use ArgumentException throw helper. # Use ArgumentException throw helper.
dotnet_diagnostic.CA1511.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1511.severity = warning
# Use ArgumentOutOfRangeException throw helper. # Use ArgumentOutOfRangeException throw helper.
dotnet_diagnostic.CA1512.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1512.severity = warning
# Use ObjectDisposedException throw helper. # Use ObjectDisposedException throw helper.
dotnet_diagnostic.CA1513.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1513.severity = warning
# Avoid redundant length argument. # Avoid redundant length argument.
dotnet_diagnostic.CA1514.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1514.severity = warning
### Naming Rules ### Naming Rules
### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/naming-warnings ### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/naming-warnings
@@ -868,8 +868,8 @@ dotnet_diagnostic.CA1843.severity = warning
# Provide memory-based overrides of async methods when subclassing 'Stream'. # Provide memory-based overrides of async methods when subclassing 'Stream'.
dotnet_diagnostic.CA1844.severity = warning dotnet_diagnostic.CA1844.severity = warning
# Use span-based 'string.Concat'. (Not available on mono) # Use span-based 'string.Concat'.
dotnet_diagnostic.CA1845.severity = none dotnet_diagnostic.CA1845.severity = warning
# Prefer AsSpan over Substring. # Prefer AsSpan over Substring.
dotnet_diagnostic.CA1846.severity = warning dotnet_diagnostic.CA1846.severity = warning
@@ -878,34 +878,34 @@ dotnet_diagnostic.CA1846.severity = warning
dotnet_diagnostic.CA1847.severity = warning dotnet_diagnostic.CA1847.severity = warning
# Call async methods when in an async method. # Call async methods when in an async method.
dotnet_diagnostic.CA1849.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1849.severity = warning
# Prefer static HashData method over ComputeHash. (Not available on mono) # Prefer static HashData method over ComputeHash.
dotnet_diagnostic.CA1850.severity = none # TODO: Change to warning once using .NET 7 or later AND once supported by mono. dotnet_diagnostic.CA1850.severity = warning
# Possible multiple enumerations of IEnumerable collection. # Possible multiple enumerations of IEnumerable collection.
#dotnet_code_quality.CA1851.enumeration_methods = #dotnet_code_quality.CA1851.enumeration_methods =
dotnet_code_quality.CA1851.linq_chain_methods = M:OpenRA.Traits.IRenderModifier.Modify* dotnet_code_quality.CA1851.linq_chain_methods = M:OpenRA.Traits.IRenderModifier.Modify*
dotnet_code_quality.CA1851.assume_method_enumerates_parameters = true dotnet_code_quality.CA1851.assume_method_enumerates_parameters = true
dotnet_diagnostic.CA1851.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1851.severity = warning
# Seal internal types. # Seal internal types.
dotnet_diagnostic.CA1852.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1852.severity = warning
# Unnecessary call to 'Dictionary.ContainsKey(key)'. # Unnecessary call to 'Dictionary.ContainsKey(key)'.
dotnet_diagnostic.CA1853.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1853.severity = warning
# Prefer the IDictionary.TryGetValue(TKey, out TValue) method. # Prefer the IDictionary.TryGetValue(TKey, out TValue) method.
dotnet_diagnostic.CA1854.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1854.severity = warning
# Use Span<T>.Clear() instead of Span<T>.Fill(). # Use Span<T>.Clear() instead of Span<T>.Fill().
dotnet_diagnostic.CA1855.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1855.severity = warning
# Incorrect usage of ConstantExpected attribute. # Incorrect usage of ConstantExpected attribute.
dotnet_diagnostic.CA1856.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1856.severity = warning
# The parameter expects a constant for optimal performance. # The parameter expects a constant for optimal performance.
dotnet_diagnostic.CA1857.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1857.severity = warning
# Use StartsWith instead of IndexOf. # Use StartsWith instead of IndexOf.
dotnet_diagnostic.CA1858.severity = warning dotnet_diagnostic.CA1858.severity = warning
@@ -917,24 +917,24 @@ dotnet_diagnostic.CA1860.severity = warning
dotnet_diagnostic.CA1862.severity = warning dotnet_diagnostic.CA1862.severity = warning
# Use 'CompositeFormat'. # Use 'CompositeFormat'.
dotnet_diagnostic.CA1863.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA1863.severity = warning
# Prefer the 'IDictionary.TryAdd(TKey, TValue)' method. # Prefer the 'IDictionary.TryAdd(TKey, TValue)' method.
dotnet_diagnostic.CA1864.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1864.severity = warning
# Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char. # Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char.
dotnet_diagnostic.CA1865.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1865.severity = warning
dotnet_diagnostic.CA1866.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1866.severity = warning
dotnet_diagnostic.CA1867.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1867.severity = warning
# Unnecessary call to 'Contains' for sets. # Unnecessary call to 'Contains' for sets.
dotnet_diagnostic.CA1868.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1868.severity = warning
# Cache and reuse 'JsonSerializerOptions' instances. # Cache and reuse 'JsonSerializerOptions' instances.
dotnet_diagnostic.CA1869.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1869.severity = warning
# Use a cached 'SearchValues' instance. # Use a cached 'SearchValues' instance.
dotnet_diagnostic.CA1870.severity = suggestion # TODO: Change to warning once using .NET 8 or later. dotnet_diagnostic.CA1870.severity = warning
# Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'. # Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'.
dotnet_diagnostic.CA1871.severity = warning dotnet_diagnostic.CA1871.severity = warning
@@ -964,7 +964,7 @@ dotnet_diagnostic.CA2016.severity = warning
dotnet_diagnostic.CA2018.severity = warning dotnet_diagnostic.CA2018.severity = warning
# ThreadStatic fields should not use inline initialization. # ThreadStatic fields should not use inline initialization.
dotnet_diagnostic.CA2019.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA2019.severity = warning
# Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types. # Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types.
dotnet_diagnostic.CA2021.severity = warning dotnet_diagnostic.CA2021.severity = warning
@@ -1041,10 +1041,10 @@ dotnet_diagnostic.CA2250.severity = warning
dotnet_diagnostic.CA2251.severity = warning dotnet_diagnostic.CA2251.severity = warning
# Ensure ThreadStatic is only used with static fields. # Ensure ThreadStatic is only used with static fields.
dotnet_diagnostic.CA2259.severity = suggestion # TODO: Change to warning once using .NET 7 or later. dotnet_diagnostic.CA2259.severity = warning
# Prefer generic overload when type is known. # Prefer generic overload when type is known.
dotnet_diagnostic.CA2263.severity = none # TODO: Change to warning once mono is dropped. dotnet_diagnostic.CA2263.severity = warning
# Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'. # Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'.
dotnet_diagnostic.CA2264.severity = warning dotnet_diagnostic.CA2264.severity = warning

View File

@@ -210,8 +210,7 @@ namespace OpenRA
using (var rsa = new RSACryptoServiceProvider()) using (var rsa = new RSACryptoServiceProvider())
{ {
rsa.ImportParameters(parameters); rsa.ImportParameters(parameters);
using (var csp = SHA1.Create()) return Convert.ToBase64String(rsa.SignHash(SHA1.HashData(data), CryptoConfig.MapNameToOID("SHA1")));
return Convert.ToBase64String(rsa.SignHash(csp.ComputeHash(data), CryptoConfig.MapNameToOID("SHA1")));
} }
} }
catch (Exception e) catch (Exception e)
@@ -236,8 +235,7 @@ namespace OpenRA
using (var rsa = new RSACryptoServiceProvider()) using (var rsa = new RSACryptoServiceProvider())
{ {
rsa.ImportParameters(parameters); rsa.ImportParameters(parameters);
using (var csp = SHA1.Create()) return rsa.VerifyHash(SHA1.HashData(data), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(signature));
return rsa.VerifyHash(csp.ComputeHash(data), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(signature));
} }
} }
catch (Exception e) catch (Exception e)
@@ -252,14 +250,12 @@ namespace OpenRA
public static string SHA1Hash(Stream data) public static string SHA1Hash(Stream data)
{ {
using var csp = SHA1.Create(); return ToHex(SHA1.HashData(data), true);
return ToHex(csp.ComputeHash(data), true);
} }
public static string SHA1Hash(byte[] data) public static string SHA1Hash(byte[] data)
{ {
using var csp = SHA1.Create(); return ToHex(SHA1.HashData(data), true);
return ToHex(csp.ComputeHash(data), true);
} }
public static string SHA1Hash(string data) public static string SHA1Hash(string data)

View File

@@ -27,8 +27,7 @@ namespace OpenRA.FileFormats
public ReplayMetadata(GameInformation info) public ReplayMetadata(GameInformation info)
{ {
if (info == null) ArgumentNullException.ThrowIfNull(info);
throw new ArgumentNullException(nameof(info));
GameInfo = info; GameInfo = info;
} }

View File

@@ -111,8 +111,7 @@ namespace OpenRA
public bool TryGetMessage(string key, out string value, object[] args = null) public bool TryGetMessage(string key, out string value, object[] args = null)
{ {
if (key == null) ArgumentNullException.ThrowIfNull(key);
throw new ArgumentNullException(nameof(key));
try try
{ {

View File

@@ -100,11 +100,9 @@ namespace OpenRA
/// <summary>Adds the player information at start-up.</summary> /// <summary>Adds the player information at start-up.</summary>
public void AddPlayer(OpenRA.Player runtimePlayer, Session lobbyInfo) public void AddPlayer(OpenRA.Player runtimePlayer, Session lobbyInfo)
{ {
if (runtimePlayer == null) ArgumentNullException.ThrowIfNull(runtimePlayer);
throw new ArgumentNullException(nameof(runtimePlayer));
if (lobbyInfo == null) ArgumentNullException.ThrowIfNull(lobbyInfo);
throw new ArgumentNullException(nameof(lobbyInfo));
// We don't care about spectators and map players // We don't care about spectators and map players
if (runtimePlayer.NonCombatant || !runtimePlayer.Playable) if (runtimePlayer.NonCombatant || !runtimePlayer.Playable)

View File

@@ -31,9 +31,9 @@ namespace OpenRA.Graphics
public interface IModelWidget public interface IModelWidget
{ {
public string Palette { get; } string Palette { get; }
public float Scale { get; } float Scale { get; }
public void Setup(Func<bool> isVisible, Func<string> getPalette, Func<string> getPlayerPalette, void Setup(Func<bool> isVisible, Func<string> getPalette, Func<string> getPlayerPalette,
Func<float> getScale, Func<IModel> getVoxel, Func<WRot> getRotation); Func<float> getScale, Func<IModel> getVoxel, Func<WRot> getRotation);
} }

View File

@@ -23,8 +23,7 @@ namespace OpenRA.Primitives
public void Add(Action a, long desiredTime) public void Add(Action a, long desiredTime)
{ {
if (a == null) ArgumentNullException.ThrowIfNull(a);
throw new ArgumentNullException(nameof(a));
lock (actions) lock (actions)
{ {

View File

@@ -21,8 +21,7 @@ namespace OpenRA
public ActorInfoDictionary(IReadOnlyDictionary<string, ActorInfo> dict) public ActorInfoDictionary(IReadOnlyDictionary<string, ActorInfo> dict)
{ {
if (dict == null) ArgumentNullException.ThrowIfNull(dict);
throw new ArgumentNullException(nameof(dict));
this.dict = new Dictionary<string, ActorInfo>(dict); this.dict = new Dictionary<string, ActorInfo>(dict);
} }

View File

@@ -21,8 +21,7 @@ namespace OpenRA.Primitives
public Cache(Func<T, U> loader, IEqualityComparer<T> c) public Cache(Func<T, U> loader, IEqualityComparer<T> c)
{ {
if (loader == null) ArgumentNullException.ThrowIfNull(loader);
throw new ArgumentNullException(nameof(loader));
this.loader = loader; this.loader = loader;
cache = new Dictionary<T, U>(c); cache = new Dictionary<T, U>(c);

View File

@@ -22,8 +22,7 @@ namespace OpenRA.Primitives
public ConcurrentCache(Func<T, U> loader, IEqualityComparer<T> c) public ConcurrentCache(Func<T, U> loader, IEqualityComparer<T> c)
{ {
if (loader == null) ArgumentNullException.ThrowIfNull(loader);
throw new ArgumentNullException(nameof(loader));
this.loader = loader; this.loader = loader;
cache = new ConcurrentDictionary<T, U>(c); cache = new ConcurrentDictionary<T, U>(c);

View File

@@ -27,8 +27,7 @@ namespace OpenRA.Primitives
protected ReadOnlyAdapterStream(Stream stream) protected ReadOnlyAdapterStream(Stream stream)
{ {
if (stream == null) ArgumentNullException.ThrowIfNull(stream);
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead) if (!stream.CanRead)
throw new ArgumentException("stream must be readable.", nameof(stream)); throw new ArgumentException("stream must be readable.", nameof(stream));

View File

@@ -65,8 +65,7 @@ namespace OpenRA.Primitives
public void CopyTo(T[] array, int arrayIndex) public void CopyTo(T[] array, int arrayIndex)
{ {
if (array == null) ArgumentNullException.ThrowIfNull(array);
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0) if (arrayIndex < 0)
throw new ArgumentNullException(nameof(arrayIndex)); throw new ArgumentNullException(nameof(arrayIndex));

View File

@@ -32,8 +32,7 @@ namespace OpenRA.Primitives
/// <param name="count">The length of the segment.</param> /// <param name="count">The length of the segment.</param>
public SegmentStream(Stream stream, long offset, long count) public SegmentStream(Stream stream, long offset, long count)
{ {
if (stream == null) ArgumentNullException.ThrowIfNull(stream);
throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek) if (!stream.CanSeek)
throw new ArgumentException("stream must be seekable.", nameof(stream)); throw new ArgumentException("stream must be seekable.", nameof(stream));
if (offset < 0) if (offset < 0)

View File

@@ -150,7 +150,7 @@ namespace OpenRA.Scripting
// Remove the namespace and the trailing "Info" // Remove the namespace and the trailing "Info"
return types.SelectMany(i => i.GetGenericArguments()) return types.SelectMany(i => i.GetGenericArguments())
.Select(g => g.Name.Split('.', StringSplitOptions.RemoveEmptyEntries).LastOrDefault()) .Select(g => g.Name.Split('.', StringSplitOptions.RemoveEmptyEntries).LastOrDefault())
.Select(s => s.EndsWith("Info", StringComparison.Ordinal) ? s.Remove(s.Length - 4, 4) : s) .Select(s => s.EndsWith("Info", StringComparison.Ordinal) ? s[..^4] : s)
.ToArray(); .ToArray();
} }
} }

View File

@@ -359,8 +359,7 @@ namespace OpenRA
public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player player, 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) bool relative, WPos pos, float volumeModifier, bool attenuateVolume)
{ {
if (ruleset == null) ArgumentNullException.ThrowIfNull(ruleset);
throw new ArgumentNullException(nameof(ruleset));
if (definition == null || DisableAllSounds || (DisableWorldSounds && soundType == SoundType.World)) if (definition == null || DisableAllSounds || (DisableWorldSounds && soundType == SoundType.World))
return false; return false;
@@ -460,8 +459,7 @@ namespace OpenRA
public bool PlayNotification(Ruleset rules, Player player, string type, string notification, string variant) public bool PlayNotification(Ruleset rules, Player player, string type, string notification, string variant)
{ {
if (rules == null) ArgumentNullException.ThrowIfNull(rules);
throw new ArgumentNullException(nameof(rules));
if (type == null || notification == null) if (type == null || notification == null)
return false; return false;

View File

@@ -75,7 +75,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
{ {
enum Format : ushort { XORPrev = 0x20, XORLCW = 0x40, LCW = 0x80 } enum Format : ushort { XORPrev = 0x20, XORLCW = 0x40, LCW = 0x80 }
class TrimmedFrame : ISpriteFrame sealed class TrimmedFrame : ISpriteFrame
{ {
public SpriteFrameType Type => SpriteFrameType.Indexed8; public SpriteFrameType Type => SpriteFrameType.Indexed8;
public Size Size { get; } public Size Size { get; }

View File

@@ -96,7 +96,7 @@ namespace OpenRA.Mods.Common.Widgets
} }
} }
class PaintMarkerTileEditorAction : IEditorAction sealed class PaintMarkerTileEditorAction : IEditorAction
{ {
[FluentReference("amount", "type")] [FluentReference("amount", "type")]
const string AddedMarkerTiles = "notification-added-marker-tiles"; const string AddedMarkerTiles = "notification-added-marker-tiles";
@@ -156,7 +156,7 @@ namespace OpenRA.Mods.Common.Widgets
} }
} }
class ClearSelectedMarkerTilesEditorAction : IEditorAction sealed class ClearSelectedMarkerTilesEditorAction : IEditorAction
{ {
[FluentReference("amount", "type")] [FluentReference("amount", "type")]
const string ClearedSelectedMarkerTiles = "notification-cleared-selected-marker-tiles"; const string ClearedSelectedMarkerTiles = "notification-cleared-selected-marker-tiles";
@@ -195,7 +195,7 @@ namespace OpenRA.Mods.Common.Widgets
} }
} }
class ClearAllMarkerTilesEditorAction : IEditorAction sealed class ClearAllMarkerTilesEditorAction : IEditorAction
{ {
[FluentReference("amount")] [FluentReference("amount")]
const string ClearedAllMarkerTiles = "notification-cleared-all-marker-tiles"; const string ClearedAllMarkerTiles = "notification-cleared-all-marker-tiles";
@@ -211,7 +211,7 @@ namespace OpenRA.Mods.Common.Widgets
this.markerLayerOverlay = markerLayerOverlay; this.markerLayerOverlay = markerLayerOverlay;
tiles = new Dictionary<int, HashSet<CPos>>(markerLayerOverlay.Tiles); tiles = new Dictionary<int, HashSet<CPos>>(markerLayerOverlay.Tiles);
var allTilesCount = tiles.Values.Select(x => x.Count).Sum(); var allTilesCount = tiles.Values.Sum(x => x.Count);
Text = FluentProvider.GetMessage(ClearedAllMarkerTiles, "amount", allTilesCount); Text = FluentProvider.GetMessage(ClearedAllMarkerTiles, "amount", allTilesCount);
} }

View File

@@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.FileFormats
var audioFormat = s.ReadInt16(); var audioFormat = s.ReadInt16();
audioType = (WaveType)audioFormat; audioType = (WaveType)audioFormat;
if (!Enum.IsDefined(typeof(WaveType), audioType)) if (!Enum.IsDefined(audioType))
throw new NotSupportedException($"Compression type {audioFormat} is not supported."); throw new NotSupportedException($"Compression type {audioFormat} is not supported.");
channels = s.ReadInt16(); channels = s.ReadInt16();

View File

@@ -17,7 +17,7 @@ namespace OpenRA.Mods.Common.FileSystem
[RequireExplicitImplementation] [RequireExplicitImplementation]
public interface IFileSystemExternalContent public interface IFileSystemExternalContent
{ {
public bool InstallContentIfRequired(ModData modData); bool InstallContentIfRequired(ModData modData);
} }
public class DefaultFileSystemLoader : IFileSystemLoader public class DefaultFileSystemLoader : IFileSystemLoader

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common
{ {
public class ItchIntegration : IGlobalModData public class ItchIntegration : IGlobalModData
{ {
class User sealed class User
{ {
[JsonProperty("url")] [JsonProperty("url")]
public string Url { get; set; } public string Url { get; set; }
@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common
public string DisplayName { get; set; } public string DisplayName { get; set; }
} }
class Root sealed class Root
{ {
public User User { get; set; } public User User { get; set; }
} }

View File

@@ -502,7 +502,7 @@ namespace OpenRA.Mods.Common.Lint
} }
} }
class Keys sealed class Keys
{ {
readonly HashSet<string> keys = new(); readonly HashSet<string> keys = new();
readonly List<(string Key, string Context)> keysWithContext = new(); readonly List<(string Key, string Context)> keysWithContext = new();

View File

@@ -59,7 +59,7 @@ namespace OpenRA.Mods.Common.Lint
{ {
// Remove the "Info" suffix. // Remove the "Info" suffix.
var traitName = traitInfo.GetType().Name; var traitName = traitInfo.GetType().Name;
traitName = traitName.Remove(traitName.Length - 4); traitName = traitName[..^4];
var fields = Utility.GetFields(traitInfo.GetType()); var fields = Utility.GetFields(traitInfo.GetType());
foreach (var field in fields) foreach (var field in fields)

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Lint
{ {
// Remove the "Info" suffix. // Remove the "Info" suffix.
var traitName = traitInfo.GetType().Name; var traitName = traitInfo.GetType().Name;
traitName = traitName.Remove(traitName.Length - 4); traitName = traitName[..^4];
var locations = traitLocation.SystemActors.ToString().Replace(", ", " or "); var locations = traitLocation.SystemActors.ToString().Replace(", ", " or ");
emitError($"`{traitName}` does not belong on `{actorInfo.Key}`. It is a system trait meant for {locations}."); emitError($"`{traitName}` does not belong on `{actorInfo.Key}`. It is a system trait meant for {locations}.");
} }

View File

@@ -567,7 +567,7 @@ namespace OpenRA.Mods.Common.Scripting
"so you must not add new triggers at the same time that you are calling this function.")] "so you must not add new triggers at the same time that you are calling this function.")]
public void Clear(Actor actor, string triggerName) public void Clear(Actor actor, string triggerName)
{ {
var trigger = (Trigger)Enum.Parse(typeof(Trigger), triggerName); var trigger = Enum.Parse<Trigger>(triggerName);
if (actor == null) if (actor == null)
throw new NullReferenceException(nameof(actor)); throw new NullReferenceException(nameof(actor));

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.Scripting
public event Action<Actor, Actor> OnProducedInternal = (a, b) => { }; public event Action<Actor, Actor> OnProducedInternal = (a, b) => { };
public event Action<Actor, Actor> OnOtherProducedInternal = (a, b) => { }; public event Action<Actor, Actor> OnOtherProducedInternal = (a, b) => { };
readonly List<Triggerable>[] triggerables = Exts.MakeArray(Enum.GetValues(typeof(Trigger)).Length, _ => new List<Triggerable>()); readonly List<Triggerable>[] triggerables = Exts.MakeArray(Enum.GetValues<Trigger>().Length, _ => new List<Triggerable>());
readonly struct Triggerable : IDisposable readonly struct Triggerable : IDisposable
{ {
@@ -526,7 +526,7 @@ namespace OpenRA.Mods.Common.Scripting
public void ClearAll() public void ClearAll()
{ {
foreach (Trigger t in Enum.GetValues(typeof(Trigger))) foreach (var t in Enum.GetValues<Trigger>())
Clear(t); Clear(t);
} }

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Mods.Common.Server
{ {
public class SkirmishLogic : ServerTrait, IClientJoined, INotifySyncLobbyInfo public class SkirmishLogic : ServerTrait, IClientJoined, INotifySyncLobbyInfo
{ {
class SkirmishSlot sealed class SkirmishSlot
{ {
[FieldLoader.Serialize(FromYamlKey = true)] [FieldLoader.Serialize(FromYamlKey = true)]
public readonly string Slot; public readonly string Slot;

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var visOptionTemplate = visibilityPanel.Get<CheckboxWidget>("VISIBILITY_TEMPLATE"); var visOptionTemplate = visibilityPanel.Get<CheckboxWidget>("VISIBILITY_TEMPLATE");
visibilityPanel.RemoveChildren(); visibilityPanel.RemoveChildren();
foreach (MapVisibility visibilityOption in Enum.GetValues(typeof(MapVisibility))) foreach (var visibilityOption in Enum.GetValues<MapVisibility>())
{ {
// To prevent users from breaking the game only show the 'Shellmap' option when it is already set. // To prevent users from breaking the game only show the 'Shellmap' option when it is already set.
if (visibilityOption == MapVisibility.Shellmap && !map.Visibility.HasFlag(visibilityOption)) if (visibilityOption == MapVisibility.Shellmap && !map.Visibility.HasFlag(visibilityOption))
@@ -311,8 +311,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
try try
{ {
if (package == null) ArgumentNullException.ThrowIfNull(package);
throw new ArgumentNullException(nameof(package));
map.Save(package); map.Save(package);

View File

@@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
this.worldRenderer = worldRenderer; this.worldRenderer = worldRenderer;
MiniYaml yaml; MiniYaml yaml;
var keyNames = Enum.GetNames(typeof(ObserverStatsPanel)); var keyNames = Enum.GetNames<ObserverStatsPanel>();
var statsHotkeys = new HotkeyReference[keyNames.Length]; var statsHotkeys = new HotkeyReference[keyNames.Length];
for (var i = 0; i < keyNames.Length; i++) for (var i = 0; i < keyNames.Length; i++)
statsHotkeys[i] = logicArgs.TryGetValue("Statistics" + keyNames[i] + "Key", out yaml) ? modData.Hotkeys[yaml.Value] : new HotkeyReference(); statsHotkeys[i] = logicArgs.TryGetValue("Statistics" + keyNames[i] + "Key", out yaml) ? modData.Hotkeys[yaml.Value] : new HotkeyReference();

View File

@@ -321,7 +321,7 @@ namespace OpenRA.Mods.Common.Widgets
if (e.Modifiers.HasModifier(Modifiers.Ctrl) && CursorPosition < Text.Length) if (e.Modifiers.HasModifier(Modifiers.Ctrl) && CursorPosition < Text.Length)
{ {
// Write directly to the Text backing field to avoid unnecessary validation // Write directly to the Text backing field to avoid unnecessary validation
text = text.Remove(CursorPosition); text = text[..CursorPosition];
CursorPosition = CursorPosition.Clamp(0, text.Length); CursorPosition = CursorPosition.Clamp(0, text.Length);
OnTextEdited(); OnTextEdited();
@@ -379,7 +379,7 @@ namespace OpenRA.Mods.Common.Widgets
if ((!isOSX && e.Modifiers.HasModifier(Modifiers.Ctrl)) || (isOSX && e.Modifiers.HasModifier(Modifiers.Alt))) if ((!isOSX && e.Modifiers.HasModifier(Modifiers.Ctrl)) || (isOSX && e.Modifiers.HasModifier(Modifiers.Alt)))
text = text[..CursorPosition] + text[GetNextWhitespaceIndex()..]; text = text[..CursorPosition] + text[GetNextWhitespaceIndex()..];
else if (isOSX && e.Modifiers.HasModifier(Modifiers.Meta)) else if (isOSX && e.Modifiers.HasModifier(Modifiers.Meta))
text = text.Remove(CursorPosition); text = text[..CursorPosition];
else else
text = text.Remove(CursorPosition, 1); text = text.Remove(CursorPosition, 1);

View File

@@ -10,7 +10,6 @@
#endregion #endregion
using System; using System;
using System.Linq;
using NUnit.Framework; using NUnit.Framework;
namespace OpenRA.Test namespace OpenRA.Test
@@ -21,7 +20,7 @@ namespace OpenRA.Test
[TestCase(TestName = "Test CPos and MPos conversion and back again.")] [TestCase(TestName = "Test CPos and MPos conversion and back again.")]
public void CoarseToMapProjection() public void CoarseToMapProjection()
{ {
foreach (var gridType in Enum.GetValues(typeof(MapGridType)).Cast<MapGridType>()) foreach (var gridType in Enum.GetValues<MapGridType>())
{ {
for (var x = 0; x < 12; x++) for (var x = 0; x < 12; x++)
{ {

View File

@@ -44,9 +44,8 @@ namespace OpenRA.Test
void AssertParseFailure(string expression, string errorMessage) void AssertParseFailure(string expression, string errorMessage)
{ {
var actualErrorMessage = Assert.Throws(typeof(InvalidDataException), var actualErrorMessage = Assert.Throws<InvalidDataException>(
() => new IntegerExpression(expression).Evaluate(testValues), () => new IntegerExpression(expression).Evaluate(testValues), expression).Message;
expression).Message;
Assert.That(errorMessage, Is.EqualTo(actualErrorMessage), expression + " ===> " + actualErrorMessage); Assert.That(errorMessage, Is.EqualTo(actualErrorMessage), expression + " ===> " + actualErrorMessage);
} }