Change to use pattern matching

This commit is contained in:
teinarss
2021-02-28 19:00:32 +01:00
committed by reaperrr
parent 7c0e4b25ae
commit d60c05eff3
35 changed files with 63 additions and 122 deletions

View File

@@ -359,8 +359,7 @@ namespace OpenRA
public override bool Equals(object obj)
{
var o = obj as Actor;
return o != null && Equals(o);
return obj is Actor o && Equals(o);
}
public bool Equals(Actor other)

View File

@@ -511,8 +511,7 @@ namespace OpenRA
public static bool IsTraitEnabled<T>(this T trait)
{
var disabledTrait = trait as IDisabledTrait;
return disabledTrait == null || !disabledTrait.IsTraitDisabled;
return !(trait is IDisabledTrait disabledTrait) || !disabledTrait.IsTraitDisabled;
}
public static T FirstEnabledTraitOrDefault<T>(this IEnumerable<T> ts)

View File

@@ -67,8 +67,7 @@ namespace OpenRA
foreach (var weapon in Weapons)
{
var projectileLoaded = weapon.Value.Projectile as IRulesetLoaded<WeaponInfo>;
if (projectileLoaded != null)
if (weapon.Value.Projectile is IRulesetLoaded<WeaponInfo> projectileLoaded)
{
try
{
@@ -82,8 +81,7 @@ namespace OpenRA
foreach (var warhead in weapon.Value.Warheads)
{
var cacher = warhead as IRulesetLoaded<WeaponInfo>;
if (cacher != null)
if (warhead is IRulesetLoaded<WeaponInfo> cacher)
{
try
{

View File

@@ -41,8 +41,7 @@ namespace OpenRA.Graphics
// See combined.vert for documentation on the channel attribute format
var attribC = r.Channel == TextureChannel.RGBA ? 0x02 : ((byte)r.Channel) << 1 | 0x01;
attribC |= samplers.X << 6;
var ss = r as SpriteWithSecondaryData;
if (ss != null)
if (r is SpriteWithSecondaryData ss)
{
sl = ss.SecondaryLeft;
st = ss.SecondaryTop;

View File

@@ -81,8 +81,7 @@ namespace OpenRA
public override bool Equals(object obj)
{
var o = obj as Hotkey?;
return o != null && o == this;
return obj is Hotkey o && (Hotkey?)o == this;
}
public override string ToString() { return "{0} {1}".F(Key, Modifiers.ToString("F")); }

View File

@@ -148,8 +148,7 @@ namespace OpenRA
{
foreach (var map in package.Contents)
{
var mapPackage = package.OpenPackage(map, modData.ModFiles) as IReadWritePackage;
if (mapPackage != null)
if (package.OpenPackage(map, modData.ModFiles) is IReadWritePackage mapPackage)
yield return mapPackage;
}
}

View File

@@ -131,8 +131,7 @@ namespace OpenRA.Primitives
{
var offset = 0L;
overallBaseStream = stream;
var segmentStream = stream as SegmentStream;
if (segmentStream != null)
if (stream is SegmentStream segmentStream)
offset += segmentStream.BaseOffset + GetOverallNestedOffset(segmentStream.BaseStream, out overallBaseStream);
return offset;
}

View File

@@ -55,8 +55,7 @@ namespace OpenRA
public override bool Equals(object obj)
{
var o = obj as float3?;
return o != null && o == this;
return obj is float3 o && (float3?)o == this;
}
public override string ToString() { return "{0},{1},{2}".F(X, Y, Z); }

View File

@@ -63,13 +63,11 @@ namespace OpenRA
sb.AppendIndentedFormatLine(indent, "Exception of type `{0}`: {1}", ex.GetType().FullName, ex.Message);
var tle = ex as TypeLoadException;
var oom = ex as OutOfMemoryException;
if (tle != null)
if (ex is TypeLoadException tle)
{
sb.AppendIndentedFormatLine(indent, "TypeName=`{0}`", tle.TypeName);
}
else if (oom != null)
else if (ex is OutOfMemoryException)
{
var gcMemoryBeforeCollect = GC.GetTotalMemory(false);
GC.Collect();

View File

@@ -73,11 +73,10 @@ namespace OpenRA.Widgets
public static T LoadWidget<T>(string id, Widget parent, WidgetArgs args) where T : Widget
{
var widget = LoadWidget(id, parent, args) as T;
if (widget == null)
throw new InvalidOperationException(
"Widget {0} is not of type {1}".F(id, typeof(T).Name));
if (LoadWidget(id, parent, args) is T widget)
return widget;
throw new InvalidOperationException("Widget {0} is not of type {1}".F(id, typeof(T).Name));
}
public static Widget LoadWidget(string id, Widget parent, WidgetArgs args)

View File

@@ -273,8 +273,7 @@ namespace OpenRA
gameInfo.DisabledSpawnPoints = OrderManager.LobbyInfo.DisabledSpawnPoints;
var echo = OrderManager.Connection as EchoConnection;
var rc = echo != null ? echo.Recorder : null;
var rc = (OrderManager.Connection as EchoConnection)?.Recorder;
if (rc != null)
rc.Metadata = new ReplayMetadata(gameInfo);
@@ -326,12 +325,10 @@ namespace OpenRA
{
effects.Add(e);
var sp = e as ISpatiallyPartitionable;
if (sp == null)
if (!(e is ISpatiallyPartitionable))
unpartitionedEffects.Add(e);
var se = e as ISync;
if (se != null)
if (e is ISync se)
syncedEffects.Add(se);
}
@@ -339,12 +336,10 @@ namespace OpenRA
{
effects.Remove(e);
var sp = e as ISpatiallyPartitionable;
if (sp == null)
if (!(e is ISpatiallyPartitionable))
unpartitionedEffects.Remove(e);
var se = e as ISync;
if (se != null)
if (e is ISync se)
syncedEffects.Remove(se);
}

View File

@@ -183,19 +183,19 @@ namespace OpenRA.Mods.Cnc.Traits
public override string IconOverlayTextOverride()
{
var info = Info as GrantPrerequisiteChargeDrainPowerInfo;
if (info == null || !Active)
if (!Active)
return null;
var info = (GrantPrerequisiteChargeDrainPowerInfo)Info;
return active ? info.ActiveText : available ? info.AvailableText : null;
}
public override string TooltipTimeTextOverride()
{
var info = Info as GrantPrerequisiteChargeDrainPowerInfo;
if (info == null || !Active)
if (!Active)
return null;
var info = (GrantPrerequisiteChargeDrainPowerInfo)Info;
return active ? info.ActiveText : available ? info.AvailableText : null;
}
}

View File

@@ -197,10 +197,9 @@ namespace OpenRA.Mods.Common.Activities
maxRange = armaments.Min(a => a.MaxRange());
var pos = self.CenterPosition;
var mobile = move as Mobile;
if (!target.IsInRange(pos, maxRange)
|| (minRange.Length != 0 && target.IsInRange(pos, minRange))
|| (mobile != null && !mobile.CanInteractWithGroundLayer(self)))
|| (move is Mobile mobile && !mobile.CanInteractWithGroundLayer(self)))
{
// Try to move within range, drop the target otherwise
if (move == null)

View File

@@ -102,12 +102,8 @@ namespace OpenRA.Mods.Common
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var reference = value as ActorInitActorReference;
if (reference != null)
if (destinationType == typeof(string) && value is ActorInitActorReference reference)
return reference.InternalName;
}
return base.ConvertTo(context, culture, value, destinationType);
}

View File

@@ -34,8 +34,7 @@ namespace OpenRA.Mods.Common.Effects
target.World.RemoveAll(effect =>
{
var flashTarget = effect as FlashTarget;
return flashTarget != null && flashTarget.target == target;
return effect is FlashTarget flashTarget && flashTarget.target == target;
});
}

View File

@@ -20,8 +20,7 @@ namespace OpenRA.Mods.Common.Lint
{
foreach (var weaponInfo in rules.Weapons)
{
var missile = weaponInfo.Value.Projectile as MissileInfo;
if (missile != null)
if (weaponInfo.Value.Projectile is MissileInfo missile)
{
var minAngle = missile.MinimumLaunchAngle.Angle;
var maxAngle = missile.MaximumLaunchAngle.Angle;
@@ -31,8 +30,7 @@ namespace OpenRA.Mods.Common.Lint
CheckLaunchAngles(weaponInfo.Key, minAngle, testMaxAngle, maxAngle, emitError);
}
var bullet = weaponInfo.Value.Projectile as BulletInfo;
if (bullet != null)
if (weaponInfo.Value.Projectile is BulletInfo bullet)
{
var minAngle = bullet.LaunchAngle[0].Angle;
var maxAngle = bullet.LaunchAngle.Length > 1 ? bullet.LaunchAngle[1].Angle : minAngle;

View File

@@ -21,9 +21,8 @@ namespace OpenRA.Mods.Common.Lint
foreach (var weaponInfo in rules.Weapons)
{
var range = weaponInfo.Value.Range;
var missile = weaponInfo.Value.Projectile as MissileInfo;
if (missile != null && missile.RangeLimit > WDist.Zero && missile.RangeLimit < range)
if (weaponInfo.Value.Projectile is MissileInfo missile && missile.RangeLimit > WDist.Zero && missile.RangeLimit < range)
emitError("Weapon `{0}`: projectile RangeLimit lower than weapon range!"
.F(weaponInfo.Key));
}

View File

@@ -325,8 +325,7 @@ namespace OpenRA.Mods.Common.Orders
foreach (var blocker in blockers)
{
CPos moveCell;
var mobile = blocker.Trait as Mobile;
if (mobile != null)
if (blocker.Trait is Mobile mobile)
{
var availableCells = adjacentTiles.Where(t => mobile.CanEnterCell(t)).ToList();
if (availableCells.Count == 0)

View File

@@ -40,9 +40,7 @@ namespace OpenRA.Mods.Common.Scripting
if (initInstance.Length > 1)
initType.GetField("InstanceName").SetValue(init, initInstance[1]);
var compositeInit = init as CompositeActorInit;
var tableValue = value as LuaTable;
if (tableValue != null && compositeInit != null)
if (value is LuaTable tableValue && init is CompositeActorInit compositeInit)
{
var args = compositeInit.InitializeArgs();
var initValues = new Dictionary<string, object>();
@@ -74,8 +72,7 @@ namespace OpenRA.Mods.Common.Scripting
}
// HACK: Backward compatibility for legacy int facings
var facingInit = init as FacingInit;
if (facingInit != null)
if (init is FacingInit facingInit)
{
if (value.TryGetClrValue(out int facing))
{

View File

@@ -117,10 +117,8 @@ namespace OpenRA.Mods.Common.Traits
{
if (!h.Key.IsIdle)
{
var act = h.Key.CurrentActivity as FindAndDeliverResources;
// Ignore this actor if FindAndDeliverResources is working fine or it is performing a different activity
if (act == null || !act.LastSearchFailed)
if (!(h.Key.CurrentActivity is FindAndDeliverResources act) || !act.LastSearchFailed)
continue;
}

View File

@@ -36,8 +36,7 @@ namespace OpenRA.Mods.Common.Traits
// The DeployTransform order does not have a position associated with it,
// so we can only queue a new transformation if something else has
// already triggered the undeploy.
var currentTransform = self.CurrentActivity as Transform;
if (!order.Queued || currentTransform == null)
if (!order.Queued || !(self.CurrentActivity is Transform currentTransform))
return;
if (!order.Queued)

View File

@@ -91,8 +91,7 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<IRenderable> RenderArmaments(Actor self, AttackBase attack)
{
// Fire ports on garrisonable structures
var garrison = attack as AttackGarrisoned;
if (garrison != null)
if (attack is AttackGarrisoned garrison)
{
var bodyOrientation = coords.Value.QuantizeOrientation(self, self.Orientation);
foreach (var p in garrison.Info.Ports)

View File

@@ -209,12 +209,10 @@ namespace OpenRA.Mods.Common.Traits
{
Func<object, bool> saveInit = init =>
{
var factionInit = init as FactionInit;
if (factionInit != null && factionInit.Value == Owner.Faction)
if (init is FactionInit factionInit && factionInit.Value == Owner.Faction)
return false;
var healthInit = init as HealthInit;
if (healthInit != null && healthInit.Value == 100)
if (init is HealthInit healthInit && healthInit.Value == 100)
return false;
// TODO: Other default values will need to be filtered

View File

@@ -303,8 +303,7 @@ namespace OpenRA.Mods.Common.Traits
if (check <= BlockedByActor.Immovable && cellFlag.HasCellFlag(CellFlag.HasMovableActor) &&
actor.Owner.RelationshipWith(otherActor.Owner) == PlayerRelationship.Ally)
{
var mobile = otherActor.OccupiesSpace as Mobile;
if (mobile != null && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable)
if (otherActor.OccupiesSpace is Mobile mobile && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable)
return false;
}
@@ -324,8 +323,7 @@ namespace OpenRA.Mods.Common.Traits
if (cellFlag.HasCellFlag(CellFlag.HasTransitOnlyActor))
{
// Transit only tiles should not block movement
var building = otherActor.OccupiesSpace as Building;
if (building != null && building.TransitOnlyCells().Contains(cell))
if (otherActor.OccupiesSpace is Building building && building.TransitOnlyCells().Contains(cell))
return false;
}
@@ -346,16 +344,11 @@ namespace OpenRA.Mods.Common.Traits
static bool IsMoving(Actor self, Actor other)
{
// PERF: Because we can be sure that OccupiesSpace is Mobile here we can save some performance by avoiding querying for the trait.
var otherMobile = other.OccupiesSpace as Mobile;
if (otherMobile == null || !otherMobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
if (!(other.OccupiesSpace is Mobile otherMobile) || !otherMobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
return false;
// PERF: Same here.
var selfMobile = self.OccupiesSpace as Mobile;
if (selfMobile == null)
return false;
return true;
return self.OccupiesSpace is Mobile;
}
public void WorldLoaded(World w, WorldRenderer wr)
@@ -466,8 +459,7 @@ namespace OpenRA.Mods.Common.Traits
var isMovable = mobile != null && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable;
var isMoving = isMovable && mobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal);
var building = actor.OccupiesSpace as Building;
var isTransitOnly = building != null && building.TransitOnlyCells().Contains(cell);
var isTransitOnly = actor.OccupiesSpace is Building building && building.TransitOnlyCells().Contains(cell);
if (isTransitOnly)
{

View File

@@ -158,8 +158,7 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<IRenderable> ITiledTerrainRenderer.RenderUIPreview(WorldRenderer wr, TerrainTemplateInfo t, int2 origin, float scale)
{
var template = t as DefaultTerrainTemplateInfo;
if (template == null)
if (!(t is DefaultTerrainTemplateInfo template))
yield break;
var ts = map.Grid.TileSize;

View File

@@ -36,8 +36,8 @@ namespace OpenRA.Mods.Common.UtilityCommands
var modData = Game.ModData = utility.ModData;
// HACK: We know that maps can only be oramap or folders, which are ReadWrite
var package = new Folder(Platform.EngineDir).OpenPackage(args[1], modData.ModFiles) as IReadWritePackage;
if (package == null)
var folder = new Folder(Platform.EngineDir);
if (!(folder.OpenPackage(args[1], modData.ModFiles) is IReadWritePackage package))
throw new FileNotFoundException(args[1]);
IEnumerable<UpdateRule> rules = null;

View File

@@ -371,9 +371,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
currentPackage = package;
currentFilename = filename;
var prefix = "";
var fs = modData.DefaultFileSystem as OpenRA.FileSystem.FileSystem;
if (fs != null)
if (modData.DefaultFileSystem is OpenRA.FileSystem.FileSystem fs)
{
prefix = fs.GetPrefix(package);
if (prefix != null)

View File

@@ -180,8 +180,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
try
{
var package = map.Package as IReadWritePackage;
if (package == null || package.Name != combinedPath)
if (!(map.Package is IReadWritePackage package) || package.Name != combinedPath)
{
selectedDirectory.Folder.Delete(combinedPath);
if (fileType == MapFileType.OraMap)

View File

@@ -273,12 +273,10 @@ namespace OpenRA.Mods.Common.Widgets
bool IsForceModifiersActive(Modifiers modifiers)
{
var fmog = world.OrderGenerator as ForceModifiersOrderGenerator;
if (fmog != null && fmog.Modifiers.HasFlag(modifiers))
if (world.OrderGenerator is ForceModifiersOrderGenerator fmog && fmog.Modifiers.HasFlag(modifiers))
return true;
var uog = world.OrderGenerator as UnitOrderGenerator;
if (uog != null && Game.GetModifierKeys().HasFlag(modifiers))
if (world.OrderGenerator is UnitOrderGenerator uog && Game.GetModifierKeys().HasFlag(modifiers))
return true;
return false;

View File

@@ -65,8 +65,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
status.GetText = statusText;
}
var timerTooltip = timer as LabelWithTooltipWidget;
if (timerTooltip != null)
if (timer is LabelWithTooltipWidget timerTooltip)
{
var connection = orderManager.Connection as ReplayConnection;
if (connection != null && connection.FinalGameTick != 0)

View File

@@ -19,8 +19,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor]
public SellOrderButtonLogic(Widget widget, World world)
{
var sell = widget as ButtonWidget;
if (sell != null)
if (widget is ButtonWidget sell)
OrderButtonsChromeUtils.BindOrderButton<SellOrderGenerator>(world, sell, "sell");
}
}
@@ -30,8 +29,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor]
public RepairOrderButtonLogic(Widget widget, World world)
{
var repair = widget as ButtonWidget;
if (repair != null)
if (widget is ButtonWidget repair)
OrderButtonsChromeUtils.BindOrderButton<RepairOrderGenerator>(world, repair, "repair");
}
}
@@ -41,8 +39,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor]
public PowerdownOrderButtonLogic(Widget widget, World world)
{
var power = widget as ButtonWidget;
if (power != null)
if (widget is ButtonWidget power)
OrderButtonsChromeUtils.BindOrderButton<PowerDownOrderGenerator>(world, power, "power");
}
}
@@ -52,8 +49,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor]
public BeaconOrderButtonLogic(Widget widget, World world)
{
var beacon = widget as ButtonWidget;
if (beacon != null)
if (widget is ButtonWidget beacon)
OrderButtonsChromeUtils.BindOrderButton<BeaconOrderGenerator>(world, beacon, "beacon");
}
}

View File

@@ -282,8 +282,7 @@ namespace OpenRA.Mods.Common.Widgets
{
var item = Children.FirstOrDefault(c =>
{
var si = c as ScrollItemWidget;
return si != null && si.ItemKey == itemKey;
return c is ScrollItemWidget si && si.ItemKey == itemKey;
});
if (item != null)
@@ -294,8 +293,7 @@ namespace OpenRA.Mods.Common.Widgets
{
var item = Children.FirstOrDefault(c =>
{
var si = c as ScrollItemWidget;
return si != null && si.IsSelected();
return c is ScrollItemWidget si && si.IsSelected();
});
if (item != null)

View File

@@ -88,9 +88,8 @@ namespace OpenRA.Mods.Common.Widgets
var useClassicMouseStyle = Game.Settings.Game.UseClassicMouseStyle;
var multiClick = mi.MultiTapCount >= 2;
var uog = World.OrderGenerator as UnitOrderGenerator;
if (uog == null)
if (!(World.OrderGenerator is UnitOrderGenerator uog))
{
ApplyOrders(World, mi);
isDragging = false;

View File

@@ -83,8 +83,7 @@ namespace OpenRA.Mods.D2k.Traits.Buildings
{
var map = self.World.Map;
var terrainInfo = self.World.Map.Rules.TerrainInfo as ITemplatedTerrainInfo;
if (terrainInfo == null)
if (!(self.World.Map.Rules.TerrainInfo is ITemplatedTerrainInfo terrainInfo))
throw new InvalidDataException("D2kBuilding requires a template-based tileset.");
var template = terrainInfo.Templates[info.ConcreteTemplate];

View File

@@ -354,14 +354,13 @@ namespace OpenRA.Platforms.Default
public void SetHardwareCursor(IHardwareCursor cursor)
{
VerifyThreadAffinity();
var c = cursor as Sdl2HardwareCursor;
if (c == null)
SDL.SDL_ShowCursor((int)SDL.SDL_bool.SDL_FALSE);
else
if (cursor is Sdl2HardwareCursor c)
{
SDL.SDL_ShowCursor((int)SDL.SDL_bool.SDL_TRUE);
SDL.SDL_SetCursor(c.Cursor);
}
else
SDL.SDL_ShowCursor((int)SDL.SDL_bool.SDL_FALSE);
}
public void SetRelativeMouseMode(bool mode)