这几行C#程序为何会崩溃
来源:百度知道 编辑:UC知道 时间:2024/05/29 01:42:16
using System;
using System.Collections.Generic;
using System.Text;
public class a
{
public a()
{
this.i = 0;
}
private int i
{
set
{
i = value;
}
get
{
return i;
}
}
}
public class b
{
static void Main(String[] args)
{
a c = new a();
}
}
这段代码运行为何会造成堆栈溢出?
using System.Collections.Generic;
using System.Text;
public class a
{
public a()
{
this.i = 0;
}
private int i
{
set
{
i = value;
}
get
{
return i;
}
}
}
public class b
{
static void Main(String[] args)
{
a c = new a();
}
}
这段代码运行为何会造成堆栈溢出?
private int i
{
set
{
i = value;
}
这里出问题了,这个地方是个无限迭代,就是说你给i属性赋值,那么这个被赋值者又再给i赋值,一直这样无限循环下去,直到内存溢出报错
你可以在class a中声明一个私有变量,如s_i,用它来储存实际的i属性值
public class a
{
private int s_i;
public a()
{
this.i = 0;
}
private int i
{
set
{
s_i = value;
}
get
{
return s_i;
}
}
}
这样就解决这个问题了,还有一点要注意,如果是属性声明为私有,那就毫无意义了,如果你只是内部用,是要留一个s_i就可以了,属性通常是给外部使用的
循环赋值给一个属性了
如果你原先有设置一个对应的字段,那就不会有这样的问题了
进入死循环,