【发布时间】:2019-08-04 01:23:09
【问题描述】:
如何设置修饰符?我想让嵌套类中的“get”为所有人公开,只为外部类设置? 错误:
索引器“Cart.CartItem.Quantity”的属性不能用于 这个上下文,因为 set 访问器是不可访问的 'Cart.CartItem.CartItem(Guid itemId, string name, decimal price, int 数量)'由于其保护级别而无法访问
代码:
public class Cart
{
public List<CartItem> CartItems { get; private set; }
public int TotalQuantity => CartItems.Sum(x => x.Quantity);
public decimal TotalPrice => CartItems.Sum(x => x.Price * x.Quantity);
public Cart()
{
CartItems = new List<CartItem>();
}
public void AddItem(Guid itemId, string name, decimal price)
{
CartItem cartItem = CartItems.Find(x => x.ItemId == itemId);
if (cartItem != null)
{
cartItem.Quantity += 1;
}
else
{
CartItems.Add(new CartItem(itemId, name, price, 1));
}
}
public class CartItem
{
public Guid ItemId { get; private set; }
public string Name { get; private set; }
public int Quantity { get; private set; }
public decimal Price { get; private set; }
private CartItem(Guid itemId, string name, decimal price, int quantity)
{
ItemId = itemId;
Name = name;
Price = price;
Quantity = quantity;
}
}
}
【问题讨论】:
-
产生这个错误的代码是什么?
-
@ZoharPeled,我认为这是一个错误 =>
cartItem.Quantity += 1;因为set在CartItem类中对于Quantity是私有的 -
@er-sho 是的,你可能是对的。
标签: c#