Menu
CoddyTech

使用构造函数

Coddy C# 类和对象基础 课程的第 11 课,共 12 课。

使用 new 关键字创建对象时,我们总是会执行一个构造方法(我们在类这一章学过)。默认情况下,C# 中的每个类都有一个空构造方法,如下所示:

class MyClass {
	public MyClass() {
	
	}
}

使用下面的语句时:

MyClass myObj = new MyClass();

实际上,我们执行的就是这个不可见的构造方法!

就像之前学过的,假设有这样一个类:

class Point {
	int x;
	int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

现在,我们可以使用这个构造方法创建多个对象,如下所示:

Point p1 = new Point(5, 3);
Point p2 = new Point(1, 2);
Point p3 = new Point(0, 0);
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

challenge icon

挑战

简单

给定的代码中有一个名为 Animal 的类,在主方法中:

  • 创建一个名为 cow 的 Animal 类型对象,类型为 "cow",声音为 “Moo”
  • 创建一个名为 dog 的 Animal 类型对象,类型为 "dog",声音为 “Woof”

亲手试试

using System;

class Animal {
    public string type;
    public string voice;
    
    public Animal(string type, string voice) {
        this.type = type;
        this.voice = voice;
    }
}

class Program {
    public static void Main(string[] args) {
        // 在这里编写代码
        
        // 不要修改这行以下的代码
        Console.WriteLine(cow.type + " is making " + cow.voice);
        Console.WriteLine(dog.type + " is making " + dog.voice);
    }
}

C# 类和对象基础中的所有课

自己练习: C# 在线编译器