在C#Web表单应用程序中为属性设置新值

时间:2016-05-13 09:15:09

标签: c# properties setter getter-setter

我在setter行上遇到此错误 “WebFormsApplication1.dll中发生了'System.StackOverflowException'类型的未处理异常” 什么是操作Property1的优雅方式,我在主页面中添加了getter和setter(请参见下文), 然后我试图在method1()中操作它,最后在onInit中调用method1()。

namespace WebFormsApplication1
{
    public partial class SiteMaster : MasterPage
    {

        public string Property1
        {
            get
            {

                return System.Configuration.ConfigurationSettings.AppSettings["key1"]; 
                //gets value from config file where pair key-value is stored
            }
            set
            {
                Property1 = value;
            }
        }

        public void method1()
        {
            Property1 = Property1 + "stringToAppend"; // manipulate property here
        }

        protected void Page_Init(object sender, EventArgs e)
        {

            method1();

            .....
        }
    }
}

在Site.Master.aspx中我有<%= Property1 %> 如果我不添加setter,则属性是只读的。也许我应该在二传手内操纵它? 我希望能够单独进行以增加模块化。 感谢

1 个答案:

答案 0 :(得分:0)

问题在于:

set
{
    Property1 = value;
}

你不能这样做,因为这里发生了递归而没有条件退出,你不能在自己的setter中设置这个属性,你应该有一些字段并在setter中设置它:

public string someValue = System.Configuration.ConfigurationSettings.AppSettings["key1"];    

public string Property1
{
    get
    {
        return someValue;
    }
    set
    {
        someValue = value;
    }
}

或者您可以使用自动属性:

C#6:

public string Property1 {get;set;} = System.Configuration.ConfigurationSettings.AppSettings["key1"]; 

或低于C#6 - 您应声明属性并在构造函数或方法中初始化它:

public string Property1 {get;set;} 

public void ConstructorOrMethod()
{
    Property1 = System.Configuration.ConfigurationSettings.AppSettings["key1"]; 
}