这两种实例方法有什么区别?

时间:2014-11-02 03:58:14

标签: c# instance

这两种实例方法有什么区别?

public class Food
{
    public int apples;
    public int oranges;
    public int bananas;

    // Constructor #1
    public Food(int a, int o, int b) 
    { 
        apples = a;
        oranges = o;
        bananas = b;
    }

// Is this an instance

public Food myFood = new Food(5, 8, 1);

// Or this 

Food.myfood(5, 8, 1)

我经验丰富的朋友说后者是实例,而不是第一个。

2 个答案:

答案 0 :(得分:0)

我假设你忘了关闭你的班级。

public class Food
{
    public int apples;
    public int oranges;
    public int bananas;

    // Constructor #1
    public Food(int a, int o, int b) 
    { 
        apples = a;
        oranges = o;
        bananas = b;
    }

} // <----  you were missing this I assume

// If the following is in your main method, then myFood is an instance
// of the Food class. 
// you can do myFood.apples = 4; // very bad btw, having public variables.
public Food myFood = new Food(5, 8, 1);

// Not even sure what this is ... because you don't have a myFood on Food.
// If you would have a static property on your Food class (Yummy), then you
// could do something like Food.Yummy = what_ever_the_type_is ... 
Food.myfood(5, 8, 1)

答案 1 :(得分:0)

我觉得人们甚至都没有读过这个问题。 答案:第一个是创造一个新的食物实例(前者)

Food myFood = new Food(3,4,5);

第二个是错误地设置值。之后f

Food myFood = new Food(3,4,5);
Console.WriteLine(myfood.Oranges) // prints 4;
myFood.Oranges = 3; // set the value of oranges for that object to 3
Console.WriteLine(myFood.Oranges); // prints 3;