首页 新闻 赞助 找找看

沒有字段,直接給屬性賦值,為什么會出錯?

0
悬赏园豆:20 [已解决问题] 解决于 2012-04-14 19:27

class Person
{
  public int Width
  {
  set { this.Width = value; }
  get { return 0; }
  }
}

Person p = new Person();
p.Width = 30;

未处理的“System.StackOverflowException”类型的异常出现在 Property.exe 中。

請問大家,當p.Width=30;時為什么會報錯呢?
聽別人說,屬性是不保存數據的,字段才保存數據,是這樣嗎?

walkingboy的主页 walkingboy | 初学一级 | 园豆:69
提问于:2012-04-14 17:56
< >
分享
最佳答案
1

你的SET操作导致了死循环。

收获园豆:15
无之无 | 大侠五级 |园豆:5095 | 2012-04-14 18:23

謝謝,這才是問題的根本!

walkingboy | 园豆:69 (初学一级) | 2012-04-14 19:26
其他回答(3)
1

set { this.Width = value; }

 

你这个Width是什么?

.Neter | 园豆:19 (初学一级) | 2012-04-14 18:14

应该这样写:注意字段的大小写.

private int width;

    public int Width     {         get { return width; }         set { width = value; }     }

支持(0) 反对(0) .Neter | 园豆:19 (初学一级) | 2012-04-14 18:16
0

你知道的太多了

public int Width

{get;set;}这样就可以了。你的那个无限递归,造成堆栈溢出了。

屬性是不保存數據的,字段才保存數據?????

属性其实包含两个方法,你这么理解:属性是用来控制字段的方法,为字段制定规则的。

前者是函数成员,一个是数据成员,you see!

以下是内部实现过程。

public int Width { get; set; }
[CompilerGenerated]
public void set_Width(int value)
{
    this.<Width>k__BackingField = value;
}
[CompilerGenerated]
public int get_Width()
{
    return this.<Width>k__BackingField;
}

收获园豆:5
Halower | 园豆:1723 (小虾三级) | 2012-04-14 18:18
0

楼上正解,调用自己造成了死循环。

lucika.zh | 园豆:62 (初学一级) | 2012-04-14 19:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册