以下Action Method
将Total
作为0
返回,即使某些值item1_price,, item9_price
等是非零的。 View
也正确显示项目值(即0.00或15.45等),但Total
显示为0。
问题:我们如何正确地完成这项工作?
public class CustomerOrdersModelView
{
public string CustomerID { get; set; }
public int FY { get; set; }
public float? item1_price { get; set; }
public float? item2_price { get; set; }
...
public float? item9_price { get; set; }
public float? Total { get; set; }
}
public async Task<IActionResult> ProductAnnualReport(string rpt)
{
var qry = from c in _context.Customers
join ord in _context.Orders
on c.CustomerID equals ord.CustomerID into co
from m in co.DefaultIfEmpty()
select new CustomerOrdersModelView
{
CustomerID = c.CustomerID,
FY = c.FY,
price = co.item1_price ?? 0,
price = co.item2_price ?? 0,
...
price = co.item9_price ?? 0,
Total = co.item1_price ?? 0 + co.item2_price ?? 0 + ....+ co.item9_price ?? 0
};
}
查看:
<tr>
<td>Item1:</td>
<td>@Model.item1_price</td>
</tr>
<tr>
<td>Item2:</td>
<td>@Model.item2_price</td>
</tr>
...
<tr>
<td>Item9:</td>
<td>@Model.item9_price</td>
</tr>
<tfoot>
<tr>
<td>TOTAL:</td>
<td>@Model.Total</td>
</tr>
</tfoot>
</table>
答案 0 :(得分:2)
float? item1_price = 0;
float? item2_price = 1;
float? item3_price = 2;
float f = item1_price ?? 0 + item2_price ?? 0 + item3_price ?? 0;
f
等于0
,因为这是表达式解析的方式,因为运算符优先级和关联性:
float f = item1_price ?? ((0 + item2_price) ?? ((0 + item3_price) ?? 0));
但这就是你的意思:
float f = (item1_price ?? 0) + (item2_price ?? 0) + (item3_price ?? 0);
始终将复杂的表达式括起来。
请参阅Section 14.2.1 of the ECMA C# Standard了解运算符优先级表(感谢@Silvermind和Eric)。优先顺序从最高到最低:*
高于+
,因此1 * 2 + 3
被解析为(1 * 2) + 3
。
Primary x.y f(x) a[x] x++ x--
new typeof checked unchecked
Unary + - ! ~ ++x --x (T)x
Multiplicative * / %
Additive + -
Shift << >>
Relational & < > <= >= is as
type-testing
Equality == !=
Logical AND &
Logical XOR ^
Logical OR |
Conditional AND &&
Conditional OR ||
Null Coalescing ??
Conditional ?:
Assignment = *= /= %= += -= <<= >>=
&= ^= |=