有没有一种方法可以使用三元运算符-或类似的方法-来选择要分配给该变量的变量? [英] Is there a way to use a ternary operator - or similar method - for picking the variable to assign to?
本文介绍了有没有一种方法可以使用三元运算符-或类似的方法-来选择要分配给该变量的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以根据条件改变我要分配的变量?我遇到的问题是想这样做:
is it possible to differ the variable I'm assigning to depending on a condition? The issue I came across is wanting to do this:
(bEquipAsSecondary ? currentWeaponOffhand : currentWeaponMainhand) = weaponToSwitchTo;
代替
if (bEquipAsSecondary)
{
currentWeaponOffhand = weaponToSwitchTo;
}
else
{
currentWeaponMainhand = weaponToSwitchTo;
}
这将导致以下错误
错误CS0131分配的左侧必须是变量,属性或索引器
Error CS0131 The left-hand side of an assignment must be a variable, property or indexer
所以我想知道是否有一种方法可以减少使用的空间,并且-依我看,使它看起来更整洁?
So I was wondering if there was a way to do this to cut down on space used and - in my opinion - make it look a bit neater?
推荐答案
To use terinary operator for picking the variable to assign value to, you could make use of ref locals/returns.For example,
(bEquipAsSecondary ? ref currentWeaponOffhand : ref currentWeaponMainhand) = weaponToSwitchTo;
示例输出和代码
var currentWeaponOffhand = 4;
var currentWeaponMainhand = 5;
var weaponToSwitchTo = 7;
(bEquipAsSecondary ? ref currentWeaponOffhand : ref currentWeaponMainhand) = weaponToSwitchTo;
Console.WriteLine($"When bEquipAsSecondary={bEquipAsSecondary},currentWeaponOffhand={currentWeaponOffhand},currentWeaponMainhand={currentWeaponMainhand}");
输出
When bEquipAsSecondary=False,currentWeaponOffhand=4,currentWeaponMainhand=7
When bEquipAsSecondary=True,currentWeaponOffhand=7,currentWeaponMainhand=5
这篇关于有没有一种方法可以使用三元运算符-或类似的方法-来选择要分配给该变量的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文