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

walkingboy 2012-04-14 05:48:17
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;時為什么會報錯呢?
聽別人說,屬性是不保存數據的,字段才保存數據,是這樣嗎?
...全文
146 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
walkingboy 2012-04-14
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
你把set理解成SetWidth方法(事实上编译后就是SetWidth方法) 然后你的代码就成了这样
SetWidth(int value)
{
SetWidth(value);
}
[/Quote]

謝謝,您這個例子很好。理解了!
唉,有時候,真的懷疑自己適不適合學編程!
暖枫无敌 2012-04-14
  • 打赏
  • 举报
回复
赋值的调用了set

set里又对自身进行赋值。。。无限递归。。
就是这个流程,还不清楚嘛??

或是你这样写也行


class Person
{
public int Width
{
get;
set;
}
}

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

happytonice 2012-04-14
  • 打赏
  • 举报
回复
混乱了
xboxeer 2012-04-14
  • 打赏
  • 举报
回复
你把set理解成SetWidth方法(事实上编译后就是SetWidth方法) 然后你的代码就成了这样
SetWidth(int value)
{
SetWidth(value);
}
walkingboy 2012-04-14
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]
引用 2 楼 的回复:

引用 1 楼 的回复:
class Person
{
private int _width;
public int Width
{
set { this._width= value; }
get { return 0; }
}
}

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


我知道這樣寫是沒問題的,……
[/Quote]

怎么會“無限遞歸”,不明白,能給我說一下執行流程不?
porschev 2012-04-14
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

引用 1 楼 的回复:
class Person
{
private int _width;
public int Width
{
set { this._width= value; }
get { return 0; }
}
}

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


我知道這樣寫是沒問題的,但我那個到底錯在哪里了?
……
[/Quote]

死循环。。

赋值的调用了set

set里又对自身进行赋值。。。无限递归。。

当然会出现这个错误
walkingboy 2012-04-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
class Person
{
private int _width;
public int Width
{
set { this._width= value; }
get { return 0; }
}
}

Person p = new Person();
p.Width = 30;
[/Quote]

我知道這樣寫是沒問題的,但我那個到底錯在哪里了?
暖枫无敌 2012-04-14
  • 打赏
  • 举报
回复
class Person
{
private int _width;
public int Width
{
set { this._width= value; }
get { return 0; }
}
}

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

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧