这是
OrderStatus
枚举:
public enum OrderStatus
{
[Display(Name = "Gözləmədə")]
Pending,
[Display(Name = "Qəbul olundu")]
Accepted,
[Display(Name = "Ləğv edildi")]
Rejected,
[Display(Name = "Çatdırıldı")]
Delivered
}
这是
Order
模特:
public class Order : BaseEntity
{
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
[StringLength(255), Required]
public string StoreName { get; set; }
[StringLength(255), Required]
public string StoreAddress { get; set; }
public double TotalPrice { get; set; }
public double RemainingBalance { get; set; }
public ShippingMethod ShippingMethod { get; set; }
public OrderStatus Status { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public IEnumerable<OrderItem> OrderItems { get; set; }
public IEnumerable<Payment> Payments { get; set; }
}
并且在
switch
中有一个OrderController
语句来过滤数据:
private async Task<IEnumerable<Order>> PaginateAsync(string status, int page)
{
ViewBag.Status = status;
ViewBag.CurrentPage = page;
int perPage = 10;
ViewBag.PerPage = perPage;
IEnumerable<Order> orders = await _context.Orders
.Include(o => o.AppUser)
.Include(o => o.OrderItems)
.Where(o => !o.IsDeleted)
.OrderByDescending(o => o.Id)
.ToListAsync();
orders = status switch
{
"pending" => orders.Where(o => (int)o.Status == 0),
"accepted" => orders.Where(o => (int)o.Status == 1),
"rejected" => orders.Where(o => (int)o.Status == 2),
"delivered" => orders.Where(o => (int)o.Status == 3),
_ => orders
};
ViewBag.PageCount = Math.Ceiling((double)orders.Count() / perPage);
return orders.Skip((page - 1) * perPage).Take(perPage);
}
我的问题是:为什么强制转换为整数是多余的?我需要将值转换为
int
以在 accepted
、rejected
和 delivered
情况下比较它们,但不是 pending
情况。为什么在 pending
情况下没有必要?
其实这只是问题,不是问题
为什么强制转换为整数是多余的
正如您所注意到的,并非所有演员表都是多余的,而是特定的演员表 - 来自
0
.
在规范中找到“隐式枚举转换”部分:
隐式枚举转换允许将具有任何整数类型
和值零的constant_expression
(§11.23)转换为任何和任何底层类型为enum_type
的nullable_value_type
。在后一种情况下,转换是通过转换为基础enum_type
并包装结果来评估的。enum_type
因此存在从
0
常量到您的枚举的隐式转换,因此不需要显式转换。因此:
const byte bZero = 0;
MyEnum me = bZero; // Compiles
MyEnum me1 = 0; // Compiles
// MyEnum me2 = 1; // Does not compile
enum MyEnum
{
None = 10,
One,
Two
}
附言
感谢@Rand Random 的指点。