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

set new value to property in C# web form application

我在 setter 行收到这个错误 "An unhandled exception of type 'System.WhosebugException' occurred in WebFormsApplication1.dll" 什么是操纵 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,则 属性 是只读的。也许我应该在 setter 内操作它? 我希望能够单独进行以增加模块化。 谢谢

问题出在这里:

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"]; 
}