120 lines
2.8 KiB
C#
120 lines
2.8 KiB
C#
using System;
|
|
|
|
namespace Lesson04
|
|
{
|
|
class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
// ========== 方法调用 ==========
|
|
Console.WriteLine("=== 方法 ===");
|
|
SayHello("无言势");
|
|
int sum = Add(10, 20);
|
|
Console.WriteLine($"10 + 20 = {sum}");
|
|
|
|
// 带默认参数
|
|
Greet();
|
|
Greet("VRC");
|
|
|
|
// ========== 类和对象 ==========
|
|
Console.WriteLine("\n=== 类和对象 ===");
|
|
Person p1 = new Person("无言势", 25);
|
|
Person p2 = new Person("玩家A", 30);
|
|
|
|
p1.SayHi();
|
|
p2.SayHi();
|
|
|
|
// ========== 静态方法 ==========
|
|
Console.WriteLine("\n=== 静态方法 ===");
|
|
int result = MathHelper.Add(100, 200);
|
|
Console.WriteLine($"100 + 200 = {result}");
|
|
|
|
double pi = MathHelper.GetPI();
|
|
Console.WriteLine($"PI ≈ {pi}");
|
|
|
|
// ========== 面向对象练习 ==========
|
|
Console.WriteLine("\n=== 麦克风类 ===");
|
|
Microphone mic = new Microphone("USB麦克风", true);
|
|
mic.ToggleListening();
|
|
mic.ToggleListening();
|
|
|
|
Console.ReadLine();
|
|
}
|
|
|
|
// ========== 方法定义 ==========
|
|
static void SayHello(string name)
|
|
{
|
|
Console.WriteLine($"你好, {name}!");
|
|
}
|
|
|
|
static int Add(int a, int b)
|
|
{
|
|
return a + b;
|
|
}
|
|
|
|
static void Greet(string name = "World")
|
|
{
|
|
Console.WriteLine($"Hello, {name}");
|
|
}
|
|
}
|
|
|
|
// ========== 类定义 ==========
|
|
class Person
|
|
{
|
|
public string name;
|
|
public int age;
|
|
|
|
// 构造函数
|
|
public Person(string name, int age)
|
|
{
|
|
this.name = name;
|
|
this.age = age;
|
|
}
|
|
|
|
public void SayHi()
|
|
{
|
|
Console.WriteLine($"我是{name},今年{age}岁");
|
|
}
|
|
}
|
|
|
|
// 静态类
|
|
static class MathHelper
|
|
{
|
|
public static int Add(int a, int b)
|
|
{
|
|
return a + b;
|
|
}
|
|
|
|
public static double GetPI()
|
|
{
|
|
return 3.14159;
|
|
}
|
|
}
|
|
|
|
// 麦克风类 - 结合项目练习
|
|
class Microphone
|
|
{
|
|
private string name;
|
|
private bool isListening;
|
|
|
|
public Microphone(string name, bool isListening)
|
|
{
|
|
this.name = name;
|
|
this.isListening = isListening;
|
|
}
|
|
|
|
public void ToggleListening()
|
|
{
|
|
isListening = !isListening;
|
|
if (isListening)
|
|
{
|
|
Console.WriteLine($"[{name}] 开始监听...");
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine($"[{name}] 停止监听");
|
|
}
|
|
}
|
|
}
|
|
}
|