gpt4 book ai didi

C# 短 if 语句

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

有没有一种方法可以在 C# 中执行此操作,而无需为现有的每个 var 类型创建一个新方法来重载?

$box = !empty($toy) : $toy ? "";  

我能想到的唯一方法是:

if (toy != null)
{
box += toy;
}

或者这个:

public string emptyFilter(string s) ...
public int emptyFilter(int i) ...
public bool emptyFilter(bool b) ...
public object emptyFilter(object o)
{
try
{
if (o != null)
{
return o.ToString();
}
else
{
return "";
}
}
catch (Exception ex)
{
return "exception thrown":
}
}

box += this.emptyFilter(toy);

我基本上想检查以确保变量/属性已设置/不为空/存在/具有值/等等...并返回它或“”而没有像上面那样荒谬的代码。

最佳答案

您可以使用 conditional operator (?:) :

string box = (toy != null) ? toy.ToString() : "";  

关于C# 短 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5284223/

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