【问题标题】:How to add get/set properties properly? [duplicate]如何正确添加获取/设置属性? [复制]
【发布时间】:2014-05-27 19:55:53
【问题描述】:

我有一个类,其中有一些属性。我已经为这些属性编写了 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 属性?

【问题讨论】:

  • 在您的情况下,FullName 属性应该只有一个 getter,因为它只应该返回其他两个属性的字符串格式。当Name1 为“a”而Name2 为“b”时,将FullName 设置为“x”有什么用?

标签: c# properties stack-overflow


【解决方案1】:

省略设置器。你不需要拥有一个,在这种情况下你不需要它。

您实际上并没有“设置”这个公共属性的值。您只需要一个返回全名的“getter”。

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

【讨论】:

    【解决方案2】:

    而不是:

    set { FullName = value; }
    

    您应该创建一个名为 _fullName 的私有成员并编写:

    set { _fullName = value; }
    

    这个:

    set { FullName = value; }
    

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

    【讨论】:

      【解决方案3】:

      您需要添加一个 backind 字段才能使其正常工作。现在,您将 FullName 设置为 FullName 的值,从而导致无限循环并因此引发异常。

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

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

      【讨论】:

        【解决方案4】:

        您正在递归调用FullName 属性,这就是您得到堆栈溢出的原因。这里有 2 个选择。

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

        FullName 属性设为只读,并且只允许客户端在Name1Name2 上调用set。:

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

        解析输入

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

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

        【讨论】:

        • 将 Name2 设置更改为 names[1],它有两次 names[0]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 2015-05-20
        • 2019-01-23
        • 1970-01-01
        相关资源
        最近更新 更多