作业帮 > ASP.NET > 教育资讯

asp.net教程:ASP.NET基础教程(二):类和对象的区别

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/14 05:59:04 ASP.NET
asp.net教程:ASP.NET基础教程(二):类和对象的区别
asp.net教程:ASP.NET基础教程(二):类和对象的区别ASP.NET
【51Test.NET-asp教程:ASP.NET基础教程(二):类和对象的区别】:
ASP.NET基础教程在上一节我们学习了什么是面向对象编程,本节我们来继续学习类和对象的区别,简单的说动物、人类这些可以称作类,而人类又包括各种各样的人,这些也可以称为对象,具体的我们来看下下面的讲解:
1.概念
     类(class)就是指一事物,对象(object)就是这一事物的实体,如:学生和大学生,学生是一个事物,大学生就是这个事物的实体。
     类是一种数据类型,特定的类型的变量与类的实例注意区别,在与很多数据有关的操作上,两者的体现是类似的,类有很多的不同类型的实体组成,包括字段,属性,方法,事件,索引器运算符,构造函数和析构函数等等,这些都是类的成员,每一个对象可以通过存储在字段中的值来表现某一定的信息,对象的取值组合表达对象现在的状态,对象都是有生命期的,程序在对象运行期间,对象就可以构造出来,此时,类中的方法就自动被调用(初始化,分配数据资源).
     类中可以定义相当的数据和方法,类通过构造函数生成对象,对象实现类的定义而且拥有具体的数据字段,类的定义必须在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;
}
}
}


例子很简单,不过还算很能体现类和对象的关系,3个学生类的图示如下
解析:学生就是描述各不同层次学生对象的特征和状态,行为的模板,如大学生当中的一员就是学生当中的一个对象的实体 ,创建完对象就可以自动调用类中的方法完成所要的操作
编译结果:

ASP.NET