【20230319】C#学习笔记之字段与属性

写一个很简单的程序来巩固一下属性与字段的区别

C#中属性对字段起一个保护的作用,是一种防止字段被输入的非法值污染的措施

字段的声明可以是如下:

class student
{
    public int id;
    public string name="";
    public int age;
}

而属性,上文说到是对字段的一种保护作用,因此属性的声明是如下一般写法:

class student
{
    private int id;
    public int Id
    {get{return id;}set{id=value;}}
}

上述代码段中id为字段,Id则为包装字段id的属性,而属性中存在的get和set的访问器在Java中多为方法,其中set为给字段赋值,而get则是获得赋值。

下面以自定义类class student为例:

在这个类中我们定义:

学生的学号不能为负数且不超过100

年龄遵循自然规律给定一个范围(1-119)

名字的输入必须为字符串

using System;
namespace MyCsharpProgram
{
    class program
    {
        static void Main(String[]args)
        {
            student stu1 =new student();
            student stu2 =new student();
            stu1.Name = "张三";
            stu1.Age = 20;
            stu1.Id = 0;
            stu2.Name = "李四";
            stu2.Age = 19;
            stu2.Id = 1;
            Console.WriteLine("姓名:{0}",stu1.Name);
            Console.WriteLine("年龄:{0}", stu1.Age);
            Console.WriteLine("学号:{0}", stu1.Id);
            Console.WriteLine("----------------------------");
            Console.WriteLine("姓名:{0}", stu2.Name);
            Console.WriteLine("年龄:{0}", stu2.Age);
            Console.WriteLine("学号:{0}", stu2.Id);
        }
    }
    class student
    {
        private int id;
        private int age;
        private string name="";
        public int Id
        {
            get { return id; }
            set 
            {
                if (value < 0 || value > 100)
                    throw new Exception("Id Inputing is Wrong");
                else
                    id = value;
            }
        }
        public int Age
        {
            get { return age; }
            set 
            {
                if (value < 0 || value > 120)
                    throw new Exception("Age Inputing is Wrong");
                age = value;

            }
        }
        public string Name
        {
            get { return name; }
            set 
            {
                if (value is string == false)
                    throw new Exception("Name Inputing is Wrong");
                else
                    name = value; 
            }
        }
    }
}

运行结果如下:

本周的笔记完结,如有错误或者写的不好的地方,烦请各位在评论区指出。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shotar0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值