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) public override bool Equals(object obj)
{ {
var o = obj as Actor; return obj is Actor o && Equals(o);
return o != null && Equals(o);
} }
public bool Equals(Actor other) public bool Equals(Actor other)

View File

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

View File

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

View File

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

View File

@@ -81,8 +81,7 @@ namespace OpenRA
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
var o = obj as Hotkey?; return obj is Hotkey o && (Hotkey?)o == this;
return o != null && o == this;
} }
public override string ToString() { return "{0} {1}".F(Key, Modifiers.ToString("F")); } 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) foreach (var map in package.Contents)
{ {
var mapPackage = package.OpenPackage(map, modData.ModFiles) as IReadWritePackage; if (package.OpenPackage(map, modData.ModFiles) is IReadWritePackage mapPackage)
if (mapPackage != null)
yield return mapPackage; yield return mapPackage;
} }
} }

View File

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

View File

@@ -55,8 +55,7 @@ namespace OpenRA
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
var o = obj as float3?; return obj is float3 o && (float3?)o == this;
return o != null && o == this;
} }
public override string ToString() { return "{0},{1},{2}".F(X, Y, Z); } 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); sb.AppendIndentedFormatLine(indent, "Exception of type `{0}`: {1}", ex.GetType().FullName, ex.Message);
var tle = ex as TypeLoadException; if (ex is TypeLoadException tle)
var oom = ex as OutOfMemoryException;
if (tle != null)
{ {
sb.AppendIndentedFormatLine(indent, "TypeName=`{0}`", tle.TypeName); sb.AppendIndentedFormatLine(indent, "TypeName=`{0}`", tle.TypeName);
} }
else if (oom != null) else if (ex is OutOfMemoryException)
{ {
var gcMemoryBeforeCollect = GC.GetTotalMemory(false); var gcMemoryBeforeCollect = GC.GetTotalMemory(false);
GC.Collect(); 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 public static T LoadWidget<T>(string id, Widget parent, WidgetArgs args) where T : Widget
{ {
var widget = LoadWidget(id, parent, args) as T; if (LoadWidget(id, parent, args) is T widget)
if (widget == null)
throw new InvalidOperationException(
"Widget {0} is not of type {1}".F(id, typeof(T).Name));
return 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) public static Widget LoadWidget(string id, Widget parent, WidgetArgs args)

View File

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

View File

@@ -183,19 +183,19 @@ namespace OpenRA.Mods.Cnc.Traits
public override string IconOverlayTextOverride() public override string IconOverlayTextOverride()
{ {
var info = Info as GrantPrerequisiteChargeDrainPowerInfo; if (!Active)
if (info == null || !Active)
return null; return null;
var info = (GrantPrerequisiteChargeDrainPowerInfo)Info;
return active ? info.ActiveText : available ? info.AvailableText : null; return active ? info.ActiveText : available ? info.AvailableText : null;
} }
public override string TooltipTimeTextOverride() public override string TooltipTimeTextOverride()
{ {
var info = Info as GrantPrerequisiteChargeDrainPowerInfo; if (!Active)
if (info == null || !Active)
return null; return null;
var info = (GrantPrerequisiteChargeDrainPowerInfo)Info;
return active ? info.ActiveText : available ? info.AvailableText : null; 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()); maxRange = armaments.Min(a => a.MaxRange());
var pos = self.CenterPosition; var pos = self.CenterPosition;
var mobile = move as Mobile;
if (!target.IsInRange(pos, maxRange) if (!target.IsInRange(pos, maxRange)
|| (minRange.Length != 0 && target.IsInRange(pos, minRange)) || (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 // Try to move within range, drop the target otherwise
if (move == null) 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) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{ {
if (destinationType == typeof(string)) if (destinationType == typeof(string) && value is ActorInitActorReference reference)
{
var reference = value as ActorInitActorReference;
if (reference != null)
return reference.InternalName; return reference.InternalName;
}
return base.ConvertTo(context, culture, value, destinationType); return base.ConvertTo(context, culture, value, destinationType);
} }

View File

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

View File

@@ -20,8 +20,7 @@ namespace OpenRA.Mods.Common.Lint
{ {
foreach (var weaponInfo in rules.Weapons) foreach (var weaponInfo in rules.Weapons)
{ {
var missile = weaponInfo.Value.Projectile as MissileInfo; if (weaponInfo.Value.Projectile is MissileInfo missile)
if (missile != null)
{ {
var minAngle = missile.MinimumLaunchAngle.Angle; var minAngle = missile.MinimumLaunchAngle.Angle;
var maxAngle = missile.MaximumLaunchAngle.Angle; var maxAngle = missile.MaximumLaunchAngle.Angle;
@@ -31,8 +30,7 @@ namespace OpenRA.Mods.Common.Lint
CheckLaunchAngles(weaponInfo.Key, minAngle, testMaxAngle, maxAngle, emitError); CheckLaunchAngles(weaponInfo.Key, minAngle, testMaxAngle, maxAngle, emitError);
} }
var bullet = weaponInfo.Value.Projectile as BulletInfo; if (weaponInfo.Value.Projectile is BulletInfo bullet)
if (bullet != null)
{ {
var minAngle = bullet.LaunchAngle[0].Angle; var minAngle = bullet.LaunchAngle[0].Angle;
var maxAngle = bullet.LaunchAngle.Length > 1 ? bullet.LaunchAngle[1].Angle : minAngle; 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) foreach (var weaponInfo in rules.Weapons)
{ {
var range = weaponInfo.Value.Range; 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!" emitError("Weapon `{0}`: projectile RangeLimit lower than weapon range!"
.F(weaponInfo.Key)); .F(weaponInfo.Key));
} }

View File

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

View File

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

View File

@@ -117,10 +117,8 @@ namespace OpenRA.Mods.Common.Traits
{ {
if (!h.Key.IsIdle) 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 // 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; continue;
} }

View File

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

View File

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

View File

@@ -209,12 +209,10 @@ namespace OpenRA.Mods.Common.Traits
{ {
Func<object, bool> saveInit = init => Func<object, bool> saveInit = init =>
{ {
var factionInit = init as FactionInit; if (init is FactionInit factionInit && factionInit.Value == Owner.Faction)
if (factionInit != null && factionInit.Value == Owner.Faction)
return false; return false;
var healthInit = init as HealthInit; if (init is HealthInit healthInit && healthInit.Value == 100)
if (healthInit != null && healthInit.Value == 100)
return false; return false;
// TODO: Other default values will need to be filtered // 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) && if (check <= BlockedByActor.Immovable && cellFlag.HasCellFlag(CellFlag.HasMovableActor) &&
actor.Owner.RelationshipWith(otherActor.Owner) == PlayerRelationship.Ally) actor.Owner.RelationshipWith(otherActor.Owner) == PlayerRelationship.Ally)
{ {
var mobile = otherActor.OccupiesSpace as Mobile; if (otherActor.OccupiesSpace is Mobile mobile && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable)
if (mobile != null && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable)
return false; return false;
} }
@@ -324,8 +323,7 @@ namespace OpenRA.Mods.Common.Traits
if (cellFlag.HasCellFlag(CellFlag.HasTransitOnlyActor)) if (cellFlag.HasCellFlag(CellFlag.HasTransitOnlyActor))
{ {
// Transit only tiles should not block movement // Transit only tiles should not block movement
var building = otherActor.OccupiesSpace as Building; if (otherActor.OccupiesSpace is Building building && building.TransitOnlyCells().Contains(cell))
if (building != null && building.TransitOnlyCells().Contains(cell))
return false; return false;
} }
@@ -346,16 +344,11 @@ namespace OpenRA.Mods.Common.Traits
static bool IsMoving(Actor self, Actor other) 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. // 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 (!(other.OccupiesSpace is Mobile otherMobile) || !otherMobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
if (otherMobile == null || !otherMobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
return false; return false;
// PERF: Same here. // PERF: Same here.
var selfMobile = self.OccupiesSpace as Mobile; return self.OccupiesSpace is Mobile;
if (selfMobile == null)
return false;
return true;
} }
public void WorldLoaded(World w, WorldRenderer wr) 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 isMovable = mobile != null && !mobile.IsTraitDisabled && !mobile.IsTraitPaused && !mobile.IsImmovable;
var isMoving = isMovable && mobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal); var isMoving = isMovable && mobile.CurrentMovementTypes.HasMovementType(MovementType.Horizontal);
var building = actor.OccupiesSpace as Building; var isTransitOnly = actor.OccupiesSpace is Building building && building.TransitOnlyCells().Contains(cell);
var isTransitOnly = building != null && building.TransitOnlyCells().Contains(cell);
if (isTransitOnly) 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) IEnumerable<IRenderable> ITiledTerrainRenderer.RenderUIPreview(WorldRenderer wr, TerrainTemplateInfo t, int2 origin, float scale)
{ {
var template = t as DefaultTerrainTemplateInfo; if (!(t is DefaultTerrainTemplateInfo template))
if (template == null)
yield break; yield break;
var ts = map.Grid.TileSize; var ts = map.Grid.TileSize;

View File

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

View File

@@ -371,9 +371,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
currentPackage = package; currentPackage = package;
currentFilename = filename; currentFilename = filename;
var prefix = ""; 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); prefix = fs.GetPrefix(package);
if (prefix != null) if (prefix != null)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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