为什么我仍然收到 "inaccessible due to its protection level" 错误?

Why am I still getting an "inaccessible due to its protection level" error?

我正在使用 WinForm 创建一个移动订购应用程序,该应用程序具有用于不同项目页面的多个用户控件。我无法使我的 cartList 存储添加的项目和我的 TeaItem class 可从其他页面访问。我环顾四周,找到了不同的解决方案,但没有任何效果。现在,我在项目中分别为我的 cartList 和 TeaItem 添加了一个 class。 (这是一家茶馆)

这是我的 "add to cart" 用户控件代码:("AddMenu.cs")

public partial class AddMenu : UserControl
{
    public AddMenu()
    {
        InitializeComponent();
    }
    public void addToCart_Click(object sender, EventArgs e)
    {
        GlobalCartList.cartList.Add(new TeaItem() { teaName = addTeaNameLabel, teaSize = addSizeComboBox.SelectedItem });
            # cartList, teaName, and teaSize give me the inaccessible errors
    }

    # more code
}

为购物车列表单独 class:("GlobalCartList.cs")

public class GlobalCartList
{
        List<TeaItem> cartList = new List<TeaItem>();
}

还有茶品:("TeaItem.cs")

public class TeaItem
{
    string teaName;
    string teaSize;
}

谁能告诉我为什么仍然出现此错误?

您正在尝试获取卡片列表,就像它是静态的一样,但它实际上是 GlobalCartList class:

的非静态成员

其次,您试图让它成为 public 成员,但 cardlist 是私有的。

  // Here you try to access like it is an static public member.
  GlobalCartList.cartList.Add(...)

要调用 cardlist,您必须将其设为 public,以便可以在 GlobalCartList class 之外调用它。其次,您必须使 cardlist 静态化,这样您就可以在不创建 GlobalCartList class.

实例的情况下调用它
public class GlobalCartList
{
    public static List<TeaItem> cartList = new List<TeaItem>();
}

然后 TeaItem 使其成为成员 public:

 public class TeaItem
 {
    public string teaName;
    public string teaSize;
 }

Note that by defautlt if not specified public infront of an member the member is private and that by default the members of an class are none static.

这是因为 List<TeaItem> cartList 默认是私有的。您应该添加 public (或内部)访问修饰符。 并且可能它应该是静态的,因为您没有实例化 GlobalCartList class.

public class GlobalCartList
{
    public static List<TeaItem> cartList = new List<TeaItem>();
}