问题1:最后两条的输入结果应为20,但是为什么是0
将 func_1改为:
public int func_1 //此为变量
{
get
{
return this.x;
}
set
{
if (value>10)
{
this.x=value;
}
else
{
this.x=0;
}
}
}
问题2:x是私有变量,为什么在进行属性设定的时候还得先进行实例化,我看的一本参考书上就是直接使用x。
因为Main方法是静态的,x字段不是静态的.
将 func_1改为:
public int func_1 //此为变量
{
get
{
return this.x;
}
set
{
if (value>10)
{
this.x=value;
}
else
{
this.x=0;
}
}
}
问题2:x是私有变量,为什么在进行属性设定的时候还得先进行实例化,我看的一本参考书上就是直接使用x。
因为Main方法是静态的,x字段不是静态的.
你的类没有构造函数,它使用默认的构造函数
Class1 bbb=new Class1();
得到x=0的一个bbb实例
以后你在bbb中调用任何成员属性,都新建了Class1 的实例,故从来没有访问过bbb自己的x
所以,你要打印bbb.x就是0,同样,你打印bbb.func_1又会新建Class1的实例,故又打印0
你在VS中debug一次就明白了。
namespace ConsoleApplication8
{
public class Class1
{
private int x;
public int func_1 //此为变量
{
get
{
return x;
}
set
{
if (value>10)
{
x=value;
}
else
{
x=0;
}
}
}
[STAThread]
static void Main(string[] args)
{
Class1 bbb=new Class1();
bbb.func_1=20;
Console.WriteLine(bbb.func_1);
}
}
}