0

问题已由csharpler回答。我不知道我在彼此内部创建了两个相同的类(在 MenuMaker 类中)......

X

X

X

这是我遇到问题的代码示例:

namespace MeatMenuProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            MenuMaker menu = new MenuMaker() { Randomizer = new Random() };
            label1.Text = menu.GetMenuItem();
            label2.Text = menu.GetMenuItem();
            label3.Text = menu.GetMenuItem();
            label4.Text = menu.GetMenuItem();
            label5.Text = menu.GetMenuItem();
            label6.Text = menu.GetMenuItem();
        }
    }
}

我做了一个MenuMaker类:

namespace MeatMenuProgram
{
    class MenuMaker
    {
        class MenuMaker {

            public Random Randomizer;
            
            string[] Meats = { "Roast beef", "Salami", "Turkey", "Ham", "Pastrami" };
            
            string[] Condiments = { "yellow mustard", "brown mustard","honey mustard", "mayo", "relish", "french dressing" };
            
            string[] Breads = { "rye", "white", "wheat", "pumpernickel","italian bread", "a roll" };

                public string GetMenuItem() {
                    string randomMeat = Meats[Randomizer.Next(Meats.Length)];

                    string randomCondiment = Condiments[Randomizer.Next(Condiments.Length)];

                    string randomBread = Breads[Randomizer.Next(Breads.Length)];

                    return randomMeat + " with " + randomCondiment + " on " + randomBread;
                
                }
            }
        }
    }

但它不编译。错误日志:

错误 1 ​​'MeatMenuProgram.MenuMaker' 不包含 'Randomizer' 的定义

错误 2“MeatMenuProgram.MenuMaker”不包含“GetMenuItem”的定义,并且找不到接受“MeatMenuProgram.MenuMaker”类型的第一个参数的扩展方法“GetMenuItem”(您是否缺少 using 指令或程序集引用?)

4

2 回答 2

1

首先,您应该使用 C# 编程约定,例如:以小写字母开头的变量、参数和字段的名称。

然后,仔细检查您的代码。你看到MeatMenuProgram命名空间了吗?是的。它包含一个MenuMaker类吗?是的,它确实。该类是否包含一个字段randomizer?不,不是的。它包含另一个也名为MenuMaker. 相反,删除内部类,所有问题都会消失:

namespace MeatMenuProgram
{
    class MenuMaker
    {
        public Random randomizer;

        string[] meats =
        { "Roast beef", "Salami", "Turkey", "Ham", "Pastrami" };

        string[] condiments =
        { "yellow mustard", "brown mustard","honey mustard" };

        string[] breads =
        { "rye", "white", "wheat", "pumpernickel" };

        public string GetMenuItem()
        {
            string randomMeat = meats[randomizer.Next(meats.Length)];
            string randomCondiment = condiments[randomizer.Next(condiments.Length)];
            string randomBread = breads[randomizer.Next(breads.Length)];

            return randomMeat + " with " + randomCondiment + " on " + randomBread;
        }
    }
}
于 2013-04-04T19:57:58.463 回答
0

正如错误所述,您的 classMenuMaker不包含您尝试访问的那些属性/方法。你必须有

public string GetMenuItem() { }
public Random Randomizer { get; set; }

在课堂MenuMaker上。

您将 MenuMaker 类嵌套在另一个同名的类中,您必须删除加倍的class MenuMaker {(以及最后的右大括号)。

于 2013-04-04T19:46:31.500 回答