如何正确添加get / set属性?

时间:2014-05-27 11:43:51

标签: c# properties stack-overflow

我有一个班级,里面有一些属性。我为这些属性编写了getter和setter。这是我的代码:

[DataMember]
public string FullName
{
    get { return string.Format("{0} {1}", this.Name1, this.Name2); }
    set { FullName = value; }
}

但问题是当我将值设置为全名时..

var customer = new Customer
{ 
    FullName = customerPhone.Customer.FullName
};

它给出了以下例外..

  

“System.StackOverflowException”类型的未处理异常

如何正确编写 set 属性?

4 个答案:

答案 0 :(得分:2)

而不是:

set { FullName = value; }

你应该做一个名为_fullName的私人成员并写:

set { _fullName = value; }

这个:

set { FullName = value; }

将再次调用FullName属性的set函数,最终得到stackoverflow。 (无限循环)

答案 1 :(得分:2)

您需要添加一个backind字段才能生效。现在,您将FullName设置为FullName的值,从而导致无限循环,从而导致异常。

public class MyClass
{
    private string fullName;

    [DataMember]
   public string FullName
   {
       get { return fullName; }
       set { fullName = value; }
   }
}

此外,在计算值的属性中允许SET似乎没有多大意义。

答案 2 :(得分:1)

您正在递归调用FullName属性,这就是为什么会出现堆栈溢出的原因。你有2个选择。

拆分属性(推荐解决方案)

FullName属性设为只读,并且仅允许客户在setName1上致电Name2。:

public string FullName
{
    get { return string.Format("{0} {1}", this.Name1, this.Name2); }
}

public string Name1 { get; set; }
public string Name2 { get; set; }

解析输入

使set属性的FullName能够解析输入:

public string FullName
{
    get { return string.Format("{0} {1}", this.Name1, this.Name2); }
    set 
    {
        //Note that this needs validation etc. applying to be robust
        var names = value.Split(" ");
        Name1 = names[0];
        Name2 = names[1];
    }
}

答案 3 :(得分:1)

省略了二传手。你不需要有一个,在这种情况下你不需要它。

你实际上并没有“设定”这个公共财产的价值。你只需要一个返回全名的“getter”。

public string FullName
{
    get { return string.Format("{0} {1}", this.Name1, this.Name2); }
}
相关问题