类与对象简介
本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 3 课,共 70 课。
类是用于创建对象的蓝图。对象是类的一个实例,包含数据和行为。
定义一个带有属性的简单类
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}添加一个构造函数来初始化对象
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
}添加一个方法来定义行为
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
public string Bark()
{
return $"{Name} says Woof!";
}
}创建一个对象(实例)并使用它
Dog myDog = new Dog("Buddy", 3);
Console.WriteLine(myDog.Bark());
Console.WriteLine($"Age: {myDog.Age}");输出:
Buddy says Woof!
Age: 3new 关键字会调用构造函数来创建类的实例。你可以从同一个类创建多个对象,每个对象的数据都不同。
挑战
简单为 Car 类添加构造函数和 Drive() 方法,完成这个类。然后在 Program.cs 中创建一个 Car 对象并使用它。
Drive() 方法应返回:"The {Brand} is driving!"
亲手试试
using System;
class Program
{
static void Main()
{
string brand = Console.ReadLine();
int year = int.Parse(Console.ReadLine());
// TODO:用输入的值创建一个 Car 对象
// TODO:打印 "Car: {brand} ({year})"
// TODO:调用 Drive() 方法并打印结果
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: C# 在线编译器