我制作了自定义用户控件,但在设置自定义属性时遇到问题。这是我遇到问题的代码,我不知道为什么我会收到堆栈溢出异常。任何帮助将不胜感激。
displayList = new List<ItemDisplay>();
foreach (var item in InventoryData2.Items)
{
ItemDisplay id = new ItemDisplay();
id.Item = item;
id.Name = item.Item.ItemNumber;
id.Location = new System.Drawing.Point(0, displayList.Count * id.Height);
displayList.Add(id);
}
public InventoryItem Item
{
get { return Item; }
set {
Item = value;
lblItemNumber.Text = Item.Item.ItemNumber;
lblTitle.Text = Item.Item.Title;
lblModel.Text = Item.Item.Model;
lblPrice.Text = Item.Item.Price.ToString();
}
}
答案 0 :(得分:8)
此属性的getter将导致无限递归:
public InventoryItem Item { get { return Item; }
设定者也是如此:
set
{
Item = value;
你可能想要这样的东西:
private InventoryItem item;
public InventoryItem Item
{
get
{
return this.item;
}
set
{
this.item = value;
lblItemNumber.Text = value.Item.ItemNumber;
lblTitle.Text = value.Item.Title;
lblModel.Text = value.Item.Model;
lblPrice.Text = value.Item.Price.ToString();
}
}
答案 1 :(得分:2)
您有“递归”属性访问权限:
public InventoryItem Item
{
get
{
return Item; // <-- "recursive" getter
}
set
{
Item = value; // <-- "recursive" setter
lblItemNumber.Text = Item.Item.ItemNumber;
lblTitle.Text = Item.Item.Title;
lblModel.Text = Item.Item.Model;
lblPrice.Text = Item.Item.Price.ToString();
}
}
这应该是这样的(带有支持字段):
private InventoryItem item;
public InventoryItem Item
{
get
{
return item;
}
set
{
item = value;
lblItemNumber.Text = item.Item.ItemNumber;
lblTitle.Text = item.Item.Title;
lblModel.Text = item.Item.Model;
lblPrice.Text = item.Item.Price.ToString();
}
}