【问题标题】:Inline if Statement not working内联 if 语句不起作用
【发布时间】:2011-09-28 21:25:39
【问题描述】:

由于某种原因,当我在这段代码中添加三元 if 语句时,会引发 NullPointerException。我不太清楚为什么……有什么想法吗?这是 jqGrid 的方法 - 返回 Json 数据。

var gridModel = from entity in vendorList.AsQueryable()
            select new
            {
                VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>",
                VendorNm = entity.VendorNm,
                Phone = (entity.Phone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone,
                City = entity.City,
                State = entity.LkState.StateAbbr
            };

你不能在那个位置有一个三元 if 语句吗?

【问题讨论】:

标签: c# jquery asp.net-mvc-2 jqgrid if-statement


【解决方案1】:
var gridModel = from entity in vendorList.AsQueryable()
    let unformattedPhone = entity.Phone??string.Empty
    select new
    {
        VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>",
        VendorNm = entity.VendorNm,
        Phone = (unformattedPhone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(unformattedPhone)) : unformattedPhone,
        City = entity.City,
        State = entity.LkState.StateAbbr
    };

这可能会解决您的问题。

【讨论】:

  • 它最终变成了entity.phone.Length &lt; 5——在某些情况下,entity.phone 为空。但是,您的解决方案看起来很有趣 - let unformattedPhone = entity.Phone??string.empty 双行?是什么意思?
  • ??检查该值是否为 NULL。如果不是 NULL,则返回该值,否则返回 ?? 之后的字符串。 :)
【解决方案2】:

一个问题,entity.Phone 是否为空?如果是这样,那就是原因。

旁注:我不得不说,这是一种存储电话号码的奇怪方式..

更新

问题出在“entity.Phone.Length”部分。如果 Phone 为空,则您无法访问它的长度属性......因此出现错误。所以你需要添加一个空测试。比如:

Phone = ((entity.Phone != null) && (entity.Phone.Length < 5)) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone

这样,如果它为空,你只是发出一个空值。

【讨论】:

  • 在某些情况下,它为空。但是,如果我有 String.Format(entity....) 或者我只是显示电话...没有错误..但是两者的结合使它不会出现。
猜你喜欢
  • 1970-01-01
  • 2012-07-16
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多