gpt4 book ai didi

c# - 使用条件运算符?避免 if 条件

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:42 25 4
gpt4 key购买 nike

我有以下 C# 代码

public Config(SConfig[] c)
{
GpsdIp = c[0].Ip;
GpsdPort = c[0].Port;

CompassIp = c[1]?.Ip;
CompassPort = c[1]?.Port;
}

CompassPort = c[1]?.Port; 发出警告(红地毯)无法将 int? 隐式转换为 int存在显式转换,您是否缺少强制转换?

我的意图是,如果 SConfig[] c 包含一个元素,它应该分配给 GpsdIpGpsdPort。如果它包含两个元素,则第二个元素应被视为 CompassIpCompassPort。如果可以的话,我真的很想避免 if condition

最佳答案

你的代码中是null conditional operator .您的正确语法应该是:

 CompassIp = c.Length > 1 ? c[1].Ip : null;
CompassPort = c.Length > 1 ? c[1].Port : 0;

PS:如果它是可编译的,你会在运行时得到一个Index out of range异常。

关于c# - 使用条件运算符?避免 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992117/

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