C# experiment
Experiment 1 C# basic programming
topic
Create a new console project under VS: such as: hello world program, and run the program to output the result. And explain the structure of a C# program:
Such as: a basic C # program contains several parts, what is the function of each part. . .
full code
using System;//导入System命名空间
namespace HelloWorldApplication//命名空间
{
/* 类名为 HelloWorld */
class HelloWorld
{
/* main函数 */
static void Main(string[] args)
{
/* 我的第一个 C# 程序 */
Console.WriteLine("Hello World!");//在控制台输出Hello World!并换行
Console.ReadKey();//等待键盘输入,防止一闪而过
}
}
}
operation result
This code is a classic "Hello World" program, used to demonstrate the basic structure and output functions of the C# language. The code is parsed as follows:
import System
namespace
It contains Console
classes for handling console input and output.
csharpCopy code
using System;
define namespace HelloWorldApplication
Namespaces are used to organize and manage code.
csharpCopy codenamespace HelloWorldApplication
{
}
define a classHelloWorld
Contains the main logic of the program.
csharpCopy codeclass HelloWorld
{
}
In a class, the method HelloWorld
defined is the entry point of the program. static
Main
csharpCopy codestatic void Main(string[] args)
{
}
In Main
the method, use Console.WriteLine
the method to print the text "Hello World!" to the console, and use the Console.ReadKey method to wait for the user to press any key.
csharpCopy codeConsole.WriteLine("Hello World!");
Console.ReadKey();
The above is the analysis of the code, which implements a simple console application, outputs "Hello World!" to the console, and waits for the user to press any key before exiting. This is the basic structure of a C# program, used to get started and demonstrate language features.
Experiment 2 C# object-oriented programming
topic
Create a console program, design a cat class, define the cat's color, age and other attributes in this class, and create a method to output "call".
Create an object of the class in the program to read and set the attribute value of cat, and call the method to output the cat's "meow"
full code
using System;
namespace HelloWorld
{
class Cat
{
private string color;//猫的颜色
private int age; //年龄字段
public int Age//年龄属性,用户对外操作age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Color//颜色属性,用户对外操作age
{
get
{
return color;
}
set
{
color = value;
}
}
public void hall()
{
Console.WriteLine("一只"+this.age+"岁"+this.color+"的猫正在叫:喵喵喵!");
}
}
class Program
{
public static void Main(string[] args)
{
Cat cat = new Cat();
cat.Age = 10;
cat.Color = "灰色";
cat.hall();
Console.ReadKey();
}
}
}
operation result
This code defines a Cat
class named and Main
creates an Cat
instance of and uses its properties and methods in the method.
define Cat
class
csharpCopy codeclass Cat
{
private string color;
private int age;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Color
{
get
{
return color;
}
set
{
color = value;
}
}
public void hall()
{
Console.WriteLine("一只"+this.age+"岁"+this.color+"的猫正在叫:喵喵喵!");
}
}
In this class, we define private fields color
and age
, which represent the color and age of the cat, respectively. These two fields are then encapsulated using the properties Age
and to provide access and setting to them. The and properties have and accessors, allowing us to get and set the cat's age and color via and . Finally, a method named is defined to output the cat's meow.Color
Age
Color
get
set
cat.Age
cat.Color
hall
Main
Use Cat
the class in the method
csharpCopy codepublic static void Main(string[] args)
{
Cat cat = new Cat();
cat.Age = 10;
cat.Color = "灰色";
cat.hall();
Console.ReadKey();
}
In Main
the method, we create an instance of type cat
called Cat
. Then, use the property accessors cat.Age
and cat.Color
to set the cat's age to 10 and color to "gray", respectively. Then, call cat.hall()
the method to output the meowing sound of the cat. Finally, use Console.ReadKey()
to wait for the user to press any key to exit the program.
Experiment 3 C# object-oriented advanced programming
topic
Create a console program, (1) define a Person class, with attributes such as name (Name), age (Age), gender (Sex), etc.; (2)
derive a Student class from the Person class, with data of three course grades Member, and has the SetScores method (input the student's 3 grades), the GetAverage method (calculate the average grade);
(3) The Student class requires its constructor to have three overloaded forms: 1. No parameters; 2. Name, age , a constructor with three parameters of gender; 3. A constructor with six parameters of name, age, gender, and grade; (
4) In the Main method of the Program class, use the three overloaded forms of Student to create an object, and call Its GetAverage method displays the average grade;
full code
using System;
namespace HelloWorld
{
class Person
{
protected string Name;
protected string Sex;
protected int Age;
}
// 派生类
class Student : Person
{
private int math;
private int english;
private int chinese;
public Student()
{
}
public string name
{
set
{
Name = value;
}
get
{
return Name;
}
}
public string sex
{
set
{
Sex = value;
}
get
{
return Sex;
}
}
public int age
{
set
{
Age = value;
}
get
{
return Age;
}
}
public Student(string Name,string Sex,int Age)
{
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
}
public Student(string Name, string Sex, int Age,int math,int english,int chinese)
{
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
this.math = math;
this.chinese = chinese;
this.english = english;
}
public void SetScores(int math,int chinese,int english)
{
this.math = math;
this.english = english;
this.chinese = chinese;
}
public void GetAverage()
{
Console.WriteLine(this.name+"的平均分为:"+((this.chinese)+(this.english)+(this.math))/3.0);
}
}
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
stu1.name = "蒲贺良";
stu1.sex = "男";
stu1.age = 21;
stu1.SetScores(100,100,100);
stu1.GetAverage();
Student stu2 = new Student("小黑","男",22);
stu2.SetScores(99,98,97);
stu2.GetAverage();
Student stu3 = new Student("小白", "男", 22,96,96,96);
stu3.GetAverage();
Console.ReadKey();
}
}
}
operation result
This code defines a Person
class and a derived class Student
, and Main
creates several Student
instances of in the method.
Define Person
class and Student
class
csharpCopy codeclass Person
{
protected string Name;
protected string Sex;
protected int Age;
}
Person
The class defines three protected fields Name
, Sex
and Age
, for the person's name, gender, and age.
csharpCopy codeclass Student : Person
{
private int math;
private int english;
private int chinese;
// 构造函数
public Student()
{
}
// 属性
public string name
{
set
{
Name = value;
}
get
{
return Name;
}
}
public string sex
{
set
{
Sex = value;
}
get
{
return Sex;
}
}
public int age
{
set
{
Age = value;
}
get
{
return Age;
}
}
// 构造函数重载
public Student(string Name, string Sex, int Age)
{
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
}
public Student(string Name, string Sex, int Age, int math, int english, int chinese)
{
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
this.math = math;
this.chinese = chinese;
this.english = english;
}
// 方法
public void SetScores(int math, int chinese, int english)
{
this.math = math;
this.english = english;
this.chinese = chinese;
}
public void GetAverage()
{
Console.WriteLine(this.name + "的平均分为:" + ((this.chinese) + (this.english) + (this.math)) / 3.0);
}
}
Student
The class is Person
a derived class of the class, which adds private fields math
, english
and chinese
, used to represent the students' grades in mathematics, English and Chinese. The class contains overloaded constructors, which are used to create Student
instances of the class based on different parameters. In addition, the class also defines attributes name
, sex
and age
are used to access and set Person
the protected fields in the class. In addition, the class defines SetScores
a method for setting the student's grade, and GetAverage
a method for calculating and outputting the student's average score.
Main
Use Student
the class in the method
static void Main(string[] args)
{
Student stu1 = new Student();
stu1.name = "蒲贺良";
stu1.sex = "男";
stu1.age = 21;
stu1.SetScores(100,100,100);
stu1.GetAverage();
Student stu2 = new Student("小黑","男",22);
stu2.SetScores(99,98,97);
stu2.GetAverage();
Student stu3 = new Student("小白", "男", 22,96,96,96);
stu3.GetAverage();
Console.ReadKey();
}
Main
Use Student
the class in the method
Experiment 4 File Processing in C#
topic
Create a console program, use the read and write file classes learned to encapsulate a file reading interface and a writing file interface, and complete the reading and writing of files.
full code
using System;
using System.IO;
namespace FileApplication
{
class File_Test
{
private string path;
public File_Test(string path)
{
this.path = path;
}
public void Read()
{
try
{
// 创建一个 StreamReader 的实例来读取文件
StreamReader sr = new StreamReader(path, false);
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
catch (Exception e)
{
// 向用户显示出错消息
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
public void Write(string[] content)
{
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string s in content)
{
sw.WriteLine(s);
}
}
}
}
class Program
{
static void Main(string[] args)
{
string Path = @"C:\Users\puheliang\Desktop\Project\CS_Project\实验4\test.txt";
File_Test f = new File_Test(Path);
string[] test = {
"任浩真帅", "任浩帅呆了", "任浩帅","好帅的任浩" };
f.Write(test);
f.Read();
}
}
}
operation result
This code demonstrates the use of the StreamReader
and StreamWriter
classes to read and write files.
define File_Test
class
csharpCopy codeclass File_Test
{
private string path;
public File_Test(string path)
{
this.path = path;
}
public void Read()
{
try
{
// 创建一个 StreamReader 的实例来读取文件
StreamReader sr = new StreamReader(path, false);
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
catch (Exception e)
{
// 向用户显示出错消息
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
public void Write(string[] content)
{
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string s in content)
{
sw.WriteLine(s);
}
}
}
}
File_Test
The class contains two methods: Read()
and Write(string[] content)
. Read()
The method uses StreamReader
the class to read the file contents and output them to the console line by line. Write(string[] content)
method uses StreamWriter
the class to write the contents of the string array content
to the file.
use File_Test
class
csharpCopy codestatic void Main(string[] args)
{
string Path = @"C:\Users\puheliang\Desktop\Project\CS_Project\实验4\test.txt";
File_Test f = new File_Test(Path);
string[] test = {
"任浩真帅", "任浩帅呆了", "任浩帅", "好帅的任浩" };
f.Write(test);
f.Read();
}
In Main
the method, we first define a file path Path
. Then, create an File_Test
instance of f
and pass in the file path. Next, an array of strings is defined test
, containing the content to be written to the file. Call f.Write(test)
the method to write the content to the file, then call f.Read()
the method to read the file and output the content to the console. Finally, use Console.ReadKey()
to wait for the user to press any key to exit the program.
Experiment 5: Use of Thread Technology
topic
Create a console program and create four threads. The function of each thread is: output 0-9, a total of 10 numbers. The output of the thread is required to be continuous output, which is realized by means of a semaphore or a mutex.
full code
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
static Mutex mutex = new Mutex();
static Semaphore sem = new Semaphore(1, 1);
public static void CallToChildThread01()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread1:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread02()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread2:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread03()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread3:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread04()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread4:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
static void Main(string[] args)
{
ThreadStart childref01 = new ThreadStart(CallToChildThread01);
Thread childThread01 = new Thread(childref01);
childThread01.Name = "Thread1";
childThread01.Start();
ThreadStart childref02 = new ThreadStart(CallToChildThread02);
Thread childThread02 = new Thread(childref02);
childThread02.Name = "Thread2";
childThread02.Start();
ThreadStart childref03 = new ThreadStart(CallToChildThread03);
Thread childThread03 = new Thread(childref03);
childThread03.Name = "Thread3";
childThread03.Start();
ThreadStart childref04 = new ThreadStart(CallToChildThread04);
Thread childThread04 = new Thread(childref04);
childThread04.Name = "Thread4";
childThread04.Start();
;
Console.ReadKey();
}
}
}
operation result
This code demonstrates the use of multiple threads for concurrent operations, and uses Mutex
and Semaphore
to achieve thread synchronization.
define thread function
csharpCopy codepublic static void CallToChildThread01()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread1:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread02()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread2:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread03()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread3:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
public static void CallToChildThread04()
{
sem.WaitOne();
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("thread4:" + i);
Thread.Sleep(5);
}
}
sem.Release();
}
Four thread functions are defined here, namely CallToChildThread01
, , CallToChildThread02
, CallToChildThread03
and CallToChildThread04
. Each function will use to sem.WaitOne()
acquire the semaphore, then do a simple loop output, and use to Thread.Sleep(5)
put the thread to sleep for 5 milliseconds, simulating some processing time. Finally, sem.Release()
the semaphore is released via .
Create and start thread
csharpCopy codeThreadStart childref01 = new ThreadStart(CallToChildThread01);
Thread childThread01 = new Thread(childref01);
childThread01.Name = "Thread1";
childThread01.Start();
ThreadStart childref02 = new ThreadStart(CallToChildThread02);
Thread childThread02 = new Thread(childref02);
childThread02.Name = "Thread2";
childThread02.Start();
ThreadStart childref03 = new ThreadStart(CallToChildThread03);
Thread childThread03 = new Thread(childref03);
childThread03.Name = "Thread3";
childThread03.Start();
ThreadStart childref04 = new ThreadStart(CallToChildThread04);
Thread childThread04 = new Thread(childref04);
childThread04.Name = "Thread4";
childThread04.Start();
In Main
the method, we create four thread instances using the start function , , and , ThreadStart
using Thread
the class . We give each thread a name, and then start the thread by calling the method.childThread01
childThread02
childThread03
childThread04
Start()
main thread wait
csharpCopy code
Console.ReadKey();
childThread01.Name = "Thread1";
childThread01.Start();
ThreadStart childref02 = new ThreadStart(CallToChildThread02);
Thread childThread02 = new Thread(childref02);
childThread02.Name = "Thread2";
childThread02.Start();
ThreadStart childref03 = new ThreadStart(CallToChildThread03);
Thread childThread03 = new Thread(childref03);
childThread03.Name = "Thread3";
childThread03.Start();
ThreadStart childref04 = new ThreadStart(CallToChildThread04);
Thread childThread04 = new Thread(childref04);
childThread04.Name = "Thread4";
childThread04.Start();
In Main
the method, we create four thread instances using the start function , , and , ThreadStart
using Thread
the class . We give each thread a name, and then start the thread by calling the method.childThread01
childThread02
childThread03
childThread04
Start()
main thread wait
csharpCopy code
Console.ReadKey();
Finally, use to Console.ReadKey()
keep the program running by having the main thread wait for the user to press any key.