实验五 类的定义与实例化
一、 实验目的
1. 理解面向对象的概念,掌握C#的定义类和创建对象的方法。 2. 区分类的不同数据成员,包括字段、属性。 3. 学会类与成员的其访问性控制。
二、 实验要求
1. 熟悉VS.Net 2010的基本操作方法
2. 认真阅读相关章节的内容,尤其是案例 3. 反复操作,直到熟练为止
三、 实验步骤
1. 请根据你认为合适的方式,编写一个学生类(Student),所有的字段的访问性都设计为私有,为每
一个私有字段设计相应的公有属性。设计相应代码测试这个类。 实验代码:
using System;
namespace ConsoleApplication1 {
class Students
{ private string name; private int age;
public Students(string name, int age) {
this.name = name; this.age = age; }
public string Name {
get { return name; } set { name = value; } }
public int Age {
get { return age; } set { age = value; } } }
class Program {
static void Main(string[] args) {
Students ostu = new Students(\
Console.WriteLine(\姓名:\年龄:\ ostu.Name = \ ostu.Age = 22;
Console.WriteLine(\姓名:\年龄:\ } } }
实验结果:
2. 请编写一个三角形类(Triangle),有三个字段分别为a, b, c代表三角形的三条边,有一个方法(getArea)
用于计算三角开的面积。设计相应代码测试这个类。 提示:请预习类的方法定义,来实现getArea方法。 实验代码:
实验结果:
using System;
using System.Windows.Forms; namespace lab5_2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) {
double a = Convert.ToDouble(textBox1.Text); double b = Convert.ToDouble(textBox2.Text); double c = Convert.ToDouble(textBox3.Text); Triangle triangle = new Triangle(a, b, c);
label4.Text = string.Format(\三角形的面积为: {0}\ }
class Triangle {
double a;
double b; double c;
public Triangle(double a, double b, double c) {
this.a = a; this.b = b; this.c = c; }
public double getArea() {
double t=(a+b+c)/2; double s;
s=Math.Sqrt(t*(t-a)*(t-b)*(t-c)); return s; } } } }
3. P99页,实验第1题。
实验代码:
private void button1_Click(object sender, EventArgs e) {
int x1, y1, x2, y2;
x1 = Convert.ToInt32(textBox1.Text); y1 = Convert.ToInt32(textBox3.Text); x2 = Convert.ToInt32(textBox2.Text); y2 = Convert.ToInt32(textBox4.Text); Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
textBox5.Text = p1.Distance(p2).ToString(); }
class Point {
public int X, Y;
public Point(int I, int J) { X = I; Y = J;} public double Distance(Point p) {
return System.Math.Sqrt((this.X-p.X)*(this.X-p.X)+(this.Y-p.Y)*(this.Y-p.Y));
} }
} }
实验结果:
四、 实验总结
在本次实验里,主要针对类的定义和使用进行了解,因为比较生疏,感觉较为困难,有些定义和声明记不住,解题的思路不太清晰明确,通过这次实验,自己能基本了解到一些定义,但不够熟练,课后要注意复习巩固,以后要加强联系。