-2

我正在动态加载控件并将文本传递给控件。但是当我设置公共财产时,我遇到了一个未经处理的异常。

我的控制是:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace g247_Test.controls
{
    public partial class carousel_guards : System.Web.UI.UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public String pcode
        {
            get
            {
                return pcode;
            }
            set
            {
                pcode = value;
            }
        }
    }
}

加载上一页上的控件:

   carousel_guards webUserControl = (carousel_guards)Page.LoadControl("~/controls/carousel-guards.ascx");

            webUserControl.pcode = "rg402eg";
            phGuardsList.Controls.Add(webUserControl);

错误发生在集合 { 说只是未处理的异常

4

3 回答 3

3

您的属性正在引用自己。您可以将其更改为:

 public String pcode { get; set; }

或者定义一个私有字符串字段并使用它:

private string _pcode;

public string Pcode
{
    get { return _pcode; }
    set { _pcode = value; }
}

如果您以大写开头的属性名称也更好,(使用Pascal 大小写

于 2012-11-13T11:53:51.110 回答
1

这很可能是堆栈溢出异常。您基本上是在告诉返回返回本身,它会永远持续下去。

您可以按照 Habib 所说的操作并使用get; set;语法糖,但如果您想要更多控制,典型的处理方法是创建一个字段来存储值,如下所示:

private string _pcode;

public string pcode { get { return _pcode; } set { _pcode = value; } }
于 2012-11-13T11:55:54.447 回答
0

执行 get 和 set 时,您引用的是属性本身;您应该 A) 有一个基础变量来保存调用者无法访问的值,或者使用 B)自动实现的属性

private string _pcode
public String pcode {
  get { return _pcode; }
  set { _pcode = value; }
} 

或者,

public String pcode { get; set; }
于 2012-11-13T11:54:34.627 回答