- 字段就是变量,用来储存数据
//字段
string _id;
string _name;
如上,_id用来保存学号,_name用来保存姓名。
- 属性有set和get块,分别对应写和读,二者至少存在一个。
//属性
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
如何快速的添加属性?
1.右击字段,选择快速操作和重构
2.选择封装字段(并使用属性)
快速添加的属性如下:
public string Name { get => _name; set => _name = value; }
完整的代码如下:
//Student.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test1
{
class Student
{
//字段
string _id;//学号
string _name;//姓名
bool _sex;//性别
DateTime _birth;//出生日期
//属性
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string Name { get => _name; set => _name = value; }
public DateTime Birth { get => _birth; set => _birth = value; }
public bool Sex { get => _sex; set => _sex = value; }
public int Age
{
get
{
return DateTime.Now.Year - Birth.Year;
}
}
}
}
//Program.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test1
{
class Program
{
static void Main(string[] args)
{
Student lzw = new Student();
lzw.Id = "182056218";
lzw.Name = "梁志文";
lzw.Sex = true;
lzw.Birth = new DateTime(2000, 11, 10);
Console.WriteLine("学号:{0}", lzw.Id);
Console.WriteLine("姓名:{0}", lzw.Name);
Console.WriteLine("性别:{0}", lzw.Sex?"男":"女");
Console.WriteLine("出生日期:{0}", lzw.Birth);
Console.WriteLine("年龄:{0}", lzw.Age);
}
}
}
运行结果
- 属性没有储存数据的能力。
从Age属性可以看出,可以获得年龄数据,但是不可设置年龄。并且Student类也没有age字段来储存年龄。