C# - 无法在主类中创建方法?

时间:2015-03-27 07:40:36

标签: c#

namespace FruitGarden
{
    class FruitGarden
    {
        private void MakeFruitBaskets()
        {
        private FruitBasket basket1 = new FruitBasket();
        private FruitBasket basket2 = new FruitBasket();
        }
        static void Main(string[] args)
        {    
        }
    }
}

我收到错误"}期待"在我的MakeFruitBaskets方法的开始括号之后,即使方法正确关闭。帮助

2 个答案:

答案 0 :(得分:4)

private声明中删除FruitBasket

    private void MakeFruitBaskets()
    {
         FruitBasket basket1 = new FruitBasket();
         FruitBasket basket2 = new FruitBasket();
    }

我认为你真正想要实现的目标如下所示。正如您现在所看到的,我们可以使用private,因为我们声明 FruitBasket字段。我们在MakeFruitBaskets方法中实例化

namespace FruitGarden
{
    class FruitGarden
    {
        private FruitBasket basket1; // Field
        private FruitBasket basket2; // Field

        public FruitGarden() // Constructor
        {
             MakeFruitBaskets();
        }

        private void MakeFruitBaskets()
        {
            basket1 = new FruitBasket();
            basket2 = new FruitBasket();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            FruitGarden fruitGarden = new FruitGarden();
            // Use fruitGarden
        } 
    }
}

答案 1 :(得分:3)

删除private中的private FruitBasket。您不能在方法的局部变量上拥有访问修饰符。