自定义类—C#基础回顾

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 ? "男" : "女"));
		}
	}
}

 

转载于:https://my.oschina.net/Sadhu/blog/1498939

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值