【问题标题】:What is the benefit of using get and set properties in this example? [duplicate]在这个例子中使用 get 和 set 属性有什么好处? [复制]
【发布时间】:2014-03-21 00:32:02
【问题描述】:

在以下示例中使用 get 和 set 属性有什么好处?:

class Program
{
    public class MyClass
    {
        private int age;

        public int persons_age
        {
            get
            {
                return age;
            }

            set
            {
                age = value;
            }
        }

    }

    static void Main(string[] args)
    {

       MyClass homer = new MyClass();

       homer.persons_age = 45; //uses the set property

       homer.persons_age = 56; //overwrites the value set by the line above to 56

       int homersage=homer.persons_age; //uses the get property

       Console.WriteLine(homersage);

    }
}

这样做和以下有什么区别?:

public class MyClass
    {
        public int age;
    }

 static void Main(string[] args)

    {

       MyClass homer = new MyClass();

       homer.age = 45;

       homer.age = 56; //overwrites the value set by the line above to 56

       int homersage=homer.age;

       Console.WriteLine(homersage);

    }

在上述两个程序的作用完全没有区别的情况下,使用 get 和 set 属性有什么好处?与客户端通过某些逻辑检查通过 set 方法将值分配给字段的能力有限的场景不同,在这种情况下,我看不到两个程序之间的任何功能差异。

此外,如果此类属性不用于类字段,一些编程书籍会使用短语“...破坏客户端代码”。有人可以解释一下吗?

谢谢。

【问题讨论】:

  • 感谢您的建议。我确实尝试使用类似的搜索词组,但无法获得相关结果。谢谢。我很感激。 :)
  • 另见C# : Auto-properties with or without backing field - preference?。如果您创建一个属性public int age { get; set; },那么这与您的第一个示例不同。
  • 您也可以使用自动属性语法,它具有类似于字段的简短声明,同时也是一个属性。与字段的唯一实际区别是它不能作为 refout 参数传递。

标签: c# visual-studio-2012 properties


【解决方案1】:

我能想到的一个答案是,使用 setter 和 getter 方法,您可以在其中添加检查或验证。与通过将其声明为 public 直接访问它不同,检查/验证将落在不同的位置并可能重复代码。 示例:

    public class MyClass
    {
        private int age;

        public int persons_age
        {
            get
            {
                return age;
            }

            set
            {
                if(value > 0)
                    age = value;
                else
                    //do something here
            }
        }

    } 

这样你就定义了你的对象的约束。

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2021-02-02
    • 2011-01-21
    • 2019-07-16
    • 1970-01-01
    • 2019-05-09
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多