写一个很简单的程序来巩固一下属性与字段的区别
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;
}
}
}
}
运行结果如下:
本周的笔记完结,如有错误或者写的不好的地方,烦请各位在评论区指出。