gpt4 book ai didi

c# - 有没有办法使用三元运算符 - 或类似的方法 - 来选择要分配给的变量?

转载 作者:太空狗 更新时间:2023-10-29 18:26:20 25 4
gpt4 key购买 nike

是否可以根据条件改变我分配给的变量?我遇到的问题是想这样做:

(bEquipAsSecondary ? currentWeaponOffhand : currentWeaponMainhand) = weaponToSwitchTo;

代替

if (bEquipAsSecondary)
{
currentWeaponOffhand = weaponToSwitchTo;
}
else
{
currentWeaponMainhand = weaponToSwitchTo;
}

导致以下错误

Error CS0131 The left-hand side of an assignment must be a variable, property or indexer

所以我想知道是否有一种方法可以减少使用的空间,并且——在我看来——让它看起来更整洁一些?

最佳答案

要使用三元运算符来选择要为其赋值的变量,您可以使用 ref locals/returns .例如,

(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

关于c# - 有没有办法使用三元运算符 - 或类似的方法 - 来选择要分配给的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com