我有以下方法调用,并且由于某种原因,C#中的语法无法正常工作。如果pkg.Library.description为null,则将其设置为字符串..“No Folder Selected”。还有另一种方法吗?
SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)
public void SendEmail(string folderdescription)
{
////
}
答案 0 :(得分:1)
SendEmail(pkg.libraryfolder.description ?? "No Folder Selected")
答案 1 :(得分:1)
我不确定为什么你写的东西不起作用,但另一种方法是使用空的合并运算符,用双问号表示,如下所示:
var x = y ?? z
如果y不为null,则x设置为y;如果y为null,则x设置为z。
以下是运营商的documentation。
答案 2 :(得分:1)
你不能解释为什么你的代码不起作用,它应该是,我的猜测是pkgs为null或libraryfolder为null。目前,您只是检查description是否为null,如果其他任何内容为null,则会出错。所以要解决这个问题,请尝试: -
SendEmail (pkg?.libraryfolder?.description == null ? "No Folder Selected" :pkg.libraryfolder.description)
public void SendEmail(string folderdescription)
{
////
}
或使用
使其更简单 SendEmail (pkg?.libraryfolder?.description ?? "No Folder Selected");