字符串三元运算符语法糖

Fed*_*ico 0 c# syntax operator-keyword

我在我的代码中这样做:

destImp.Cap = (addr.location.postcode != "?") ? addr.location.postcode : null;
destImp.Civico = (addr.location.street != "?") ? addr.location.street : null;
destImp.Localita = (addr.location.city != "?") ? addr.location.city : null;
destImp.Indirizzo = (addr.location.street != "?") ? addr.location.street : null;
Run Code Online (Sandbox Code Playgroud)

但这很麻烦且多余.有一种方法可以实现相同的结果,但语法更好?

Lee*_*Lee 9

您可以创建一个扩展方法:

public static string NullIf(this string str, string nullMarker)
{
   return str == nullMarker ? null : str;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

destImp.Cap = addr.location.postcode.NullIf("?");
...
Run Code Online (Sandbox Code Playgroud)