【问题标题】:string ternary operator syntactic sugar字符串三元运算符语法糖
【发布时间】:2014-04-10 10:15:24
【问题描述】:

我在我的代码中这样做:

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;

但它既麻烦又多余。有没有更好的语法来实现相同的结果?

【问题讨论】:

  • 您可以在string 上定义一个扩展方法,称为NullIf() 来结束这个测试。
  • 您至少可以编写一个方法(或本地 lambda)来执行此操作。
  • 有没有办法阻止? 出现在这些字段中?如果一条街道被称为? 怎么办?

标签: c# syntax operator-keyword


【解决方案1】:

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

public static string NullIf(this string str, string nullMarker)
{
   return str == nullMarker ? null : str;
}

那么你可以这样做:

destImp.Cap = addr.location.postcode.NullIf("?");
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2015-03-25
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多