内联 if 语句不起作用
由于某种原因,当我将三元 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 语句吗?
For some reason, when I add the ternary if statement to this bit of code, a NullPointerException is thrown. I'm not sure quite why...any ideas? This is the method for jqGrid - returning the Json data.
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
};
Can you not have a ternary if statement in that location?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会解决您的问题。
This may solve your problem.
一个问题,entity.Phone 是否为 null?如果是这样的话,那就是原因了。
旁注:我不得不说,这是一种奇怪的存储电话号码的方式。
更新
问题出在“entity.Phone.Length”部分。如果 Phone 为 null,则您无法访问它的 length 属性...因此会出现错误。所以你需要添加一个空测试。像这样:
这样,如果它为 null,您只是发出一个 null 值。
One question, is entity.Phone null? If so, that would be the cause.
Side note: I have to say, that is an odd way of storing a phone number..
UPDATE
The problem is with the "entity.Phone.Length" part. If Phone is null, then you can't access it's length property... hence the error. So you need to add a null test. Something like:
That way, if it is null you are just emitting a null value.