类中可以定义相当的数据和方法,类通过构造函数生成对象,对象实现类的定义而且拥有具体的数据字段,类的定义必须在Class关键字之后的大括号内完成,而对象的创建是使用new关键符来操作(即使没有参数但是也要写一对空的圆括号来表现下这个是无参数的构造函数).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CObject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入学生对象的类型(Schoolchild,M_Student,Undergraduate)");
string type = Console.ReadLine();
Console.WriteLine("请输入学生对象的体重");
string height = Console.ReadLine();
Console.WriteLine("请输入学生对象的类型代号(1代表Schoolchild,2代表M_Student,3代表Undergraduate)");
int num = Convert.ToInt32(Console.ReadLine());
switch (num)
{
case 1:
Schoolchild sc = new Schoolchild(type, height);
Console.WriteLine("你创建一位名字叫"+Schoolchild.name+"的人");
Console.WriteLine("他是一名"+sc.type);
Console.WriteLine("他的身高是"+sc.height+"cm");
Console.WriteLine(Schoolchild.Message);
break;
case 2:
M_Student ms = new M_Student(type, height);
Console.WriteLine("你创建一位名字叫" + M_Student.name + "的人");
Console.WriteLine("他是一名" + ms.type);
Console.WriteLine("他的身高是" + ms.height + "cm");
Console.WriteLine(M_Student.Message);
break;
case 3:
Undergraduate un=new Undergraduate(type, height);
Console.WriteLine("你创建一位名字叫" + Undergraduate.name + "的人");
Console.WriteLine("他是一名" + un.type);
Console.WriteLine("他的身高是" + un.height + "cm");
Console.WriteLine(Undergraduate.Message);
break;
default:
Console.WriteLine("对不起,你输入有误,请重新输入!!");
break;
}
Console.ReadLine();
}
}
class Schoolchild //小学生类
{
internal static string name = "小明";
internal static string Message = "小明在小学校园捡到一分钱";
internal string type;//学生类型
internal string height;//身高
internal Schoolchild(string type, string height)
{
this.type = type;
this.height = height;
}
}
class M_Student //中学生类
{
internal static string name = "小红";
internal static string Message = "小红在中学校园捡到一块钱";
internal string type;//学生类型
internal string height;//身高
internal M_Student(string type, string height)
{
this.type = type;
this.height = height;
}
}
class Undergraduate //大学生类
{
internal static string name = "类菌体";
internal static string Message = "类菌体在大学校园捡到一百块钱";
internal string type;//学生类型
internal string height;//身高
internal Undergraduate(string type, string height)
{
this.type = type;
this.height = height;
}
}
}