首页 > 解决方案 > 定义如下所示的属性有什么意义?它在密封化的背景下带来了什么?

问题描述

我读了很多关于属性和封装的文章,但我不明白什么时候应该为属性使用缩短的代码条目,什么时候可以在实践中使用属性。

下面是我找到并修改的属性和变量定义的一些示例。我认为,我正确理解了它们中的每一个是如何工作的,但我看不出在实践中使用它们中的一些的意义。

class MyClass
    {
        //1 - read and write property short record
        public string Name1 { get; set; } = "Name1 content";

        //2 - variable instead of property from 1 ex.
        public string Name2 = "Name2 content";

        //3 - read and write property long record
        private string _name3 = default(string);
        public string Name3
        {
            get => _name3;
            set => _name3 = value;
        }

        //4 - read and write property with checking of value
        private string _name4 = default(string);
        public string Name4
        {
            get
            {
                return _name4;
            }
            set
            {
                if (value.Length >= 3)
                    _name4 = value;
            }
        }

        //5 - read only property short record
        public string Name5 { get; } = "Name5 content";

        //6 - read only variable
        public static readonly string Name6 = "Name6 content";

        //7 - read (public) and write (in class range) property
        private string _name7 = default(string);

        public MyClass(string n)
        {
            this._name7 = n;
        }

        public string Name7
        {
            get => _name4;
            private set => _name7 = value;
        }
    }

前任。1 完全像这样声明属性而不是变量(例 2)有什么好处?我知道,与字段(变量)相反,属性可以在接口中使用,但是,还有其他优势吗?

前任。3 对我来说毫无意义,但它在大多数属性应用示例中都有体现。它不提供(在我看来)_name3 的封装,因为 Name3 的每次更改(从外部)都会导致 _name3 的更改(在 MyClass 中)

前任。4对我来说很有意义。但是在实践中使用的属性是否仅用于检查输入条件?它可以在构造函数中完成。

前任。5和前。6类似于Ex。1和前。2. 如果我想阻止更改 Name5 值的可能性,我可以使用只读变量而不是属性(如例 6 中所示)。

前任。图 7 是我发现并修改的唯一使用属性进行封装的示例。_name7/Name7 只能通过构造函数从外部设置。然后我只能从 MyClass 中更改它。

除了回答我的疑问之外,你能否给我一些最常见的实际使用属性的例子?

标签: c#properties

解决方案


推荐阅读