17.属性

什么是属性?

属性类似于java中的setter和getter方法,其本质上就是get和set方法

属性的作用?

属性的作用就是保护字段、对字段的赋值和取值进行限定。

基本语法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo {


    class Program {

        //字段
        private string _name;
        private int _age;

        //属性
        public string Name {
            get;
            set;
        }

        public int Age {
            get;
            set;
        }

    }
}

上述可以看做一个简写。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo {


    class Program {

        //字段
        private string _name;
        private int _age;

        //属性
        public string Name {
            get { return _name; }
            set { _name = value; }
        }

        public int Age {
            get { return _age; }
            set { _age = value; }
        }
    }
}

使用属性可以对字段进行保护,当字段的值有某些范围时,例如_age不可为负数,那么这时就可以在属性中进行一个限制,如下例代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo {


    class Program {

        //字段
        private string _name;
        private int _age;

        //属性
        public string Name {
            get { return _name; }
            set { _name = value; }
        }

        public int Age {
            get { return _age; }
            set {
                if (value < 0) {
                    value = 0;
                }
                _age = value;
            }
        }
    }

    class Test {
        static void Main(string[] args) {
            Program p = new Program();
            p.Name = "zs";
            p.Age = -1;

        }
    }
}

当通过debug模式调试时,会发现_age最后是为0的。

总结

既有get()也有set()我们诚之为可读可写属性。
只有get()没有set()我们称之为只读属性
没有get()只有set()我们称之为只写属性

猜你喜欢

转载自www.cnblogs.com/lz32158/p/12892306.html
今日推荐