这两种实例方法之间的区别是什么
本文关键字:区别 是什么 之间 两种 实例方法 | 更新日期: 2023-09-27 18:28:56
这两个实例方法之间有什么区别?
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)
我更有经验的朋友说,是后一种情况,而不是第一种。
我觉得人们甚至没有阅读这个问题。答案:第一个是创建一个新的食品实例(前者)
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;
我假设您忘记关闭类了。
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)