3.1.cs
/*
author:frank
datetime:2017年8月1日11:04:39
类和结构基本上差不多,但是存储的地方不一样,结构不支持继承,类是存储在堆(heap)上的,结构是存储在栈(stack)上的。由于栈比堆的速度要高一些,所以小型数据可以使用结构体。
*/
using System;
namespace Sample
{
public class Program
{
public static void Main(string[] args)
{
Student student = new Student("张三",22,1);
student.PrintInfo();
Student student2 = new Student("李丽",0,2);
student2.PrintInfo();
}
}
///<smmary>
/// 学生
///</smmary>
public class Student
{
<summary>
学校名称
</summary>
public const string SchoolName = "北京大学";
///<summary>
///昵称
///</summary>
public readonly string Nickname;
///<summary>
///备注
///</summary>
public static readonly string Remark;
private string _name;
///<summary>
///姓名
///</summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private int _age;
///<summary>
///年龄
///</summary>
public int Age
{
get
{
return _age;
}
set
{
if(value <= 18)
{
_age = 18;
}
else
{
_age = value;
}
}
}
private short _sex;
///<summary>
///性别
///</summary>
public short Sex
{
get
{
return _sex;
}
private set
{
_sex = value;
}
}
public Student(string name,int age,short sex)
{
this.Name = name;
this.Age = age;
this.Sex = sex;
}
public Student(string name,int age):this(name,age,18)//调用另外一个构造函数
{
this.Nickname = "王五";//只能在构造函数或者初始化的时候赋值,其他地方赋值就会报错。且只能赋值一次
}
static Student()//静态构造函数由.net运行库调用,不确定什么时候会执行,但是一定是在类实例化前。
{
Remark = "线上";//只读属性只能赋值一次
Console.WriteLine("学生类静态构造函数");
}
public void PrintInfo()
{
Console.WriteLine("SchoolName:{0},Name:{1},Age:{2},Sex:{3}",Student.SchoolName,this.Name,this.Age,(this.Sex == 1 ? "男" : "女"));
}
}
}