适合每位开发人员的 60 个 C# 代码片段("60个C#代码片段:每位开发人员的实用宝典")

原创
ithorizon 6个月前 (10-20) 阅读数 58 #后端开发

60个C#代码片段:每位开发人员的实用宝典

一、基础语法

以下是一些基础的C#代码片段,涵盖了变量声明、数据类型转换、条件判断等。

1. 变量声明

int number = 10;

string text = "Hello, World!";

float pi = 3.14f;

double area = 12.5;

bool isTrue = true;

2. 数据类型转换

int intValue = 10;

double doubleValue = (double)intValue;

string stringValue = intValue.ToString();

3. 条件判断

int age = 18;

if (age >= 18)

{

Console.WriteLine("You are an adult.");

}

else

{

Console.WriteLine("You are not an adult.");

}

二、面向对象编程

以下是一些涉及面向对象编程的代码片段,包括类的定义、继承、多态等。

1. 类的定义与使用

public class Person

{

public string Name { get; set; }

public int Age { get; set; }

public Person(string name, int age)

{

Name = name;

Age = age;

}

public void Introduction()

{

Console.WriteLine($"My name is {Name} and I am {Age} years old.");

}

}

Person person = new Person("John", 25);

person.Introduction();

2. 继承

public class Student : Person

{

public string StudentID { get; set; }

public Student(string name, int age, string studentID) : base(name, age)

{

StudentID = studentID;

}

public void ShowStudentID()

{

Console.WriteLine($"Student ID: {StudentID}");

}

}

Student student = new Student("Alice", 20, "S12345");

student.Introduction();

student.ShowStudentID();

3. 多态

public interface IShape

{

void Draw();

}

public class Circle : IShape

{

public void Draw()

{

Console.WriteLine("Drawing a circle.");

}

}

public class Rectangle : IShape

{

public void Draw()

{

Console.WriteLine("Drawing a rectangle.");

}

}

IShape shape1 = new Circle();

IShape shape2 = new Rectangle();

shape1.Draw();

shape2.Draw();

三、数据结构

以下是一些涉及数据结构的代码片段,包括数组、列表、字典等。

1. 数组

int[] numbers = { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)

{

Console.WriteLine(numbers[i]);

}

2. 列表

List numbersList = new List { 1, 2, 3, 4, 5 };

foreach (int number in numbersList)

{

Console.WriteLine(number);

}

3. 字典

Dictionary dictionary = new Dictionary();

dictionary.Add(1, "One");

dictionary.Add(2, "Two");

dictionary.Add(3, "Three");

foreach (KeyValuePair pair in dictionary)

{

Console.WriteLine($"{pair.Key}: {pair.Value}");

}

四、文件操作

以下是一些涉及文件操作的代码片段,包括文件的读取、写入、复制等。

1. 文件读取

string filePath = "example.txt";

string content = File.ReadAllText(filePath);

Console.WriteLine(content);

2. 文件写入

string filePath = "example.txt";

string content = "Hello, World!";

File.WriteAllText(filePath, content);

3. 文件复制

string sourceFilePath = "example.txt";

string destinationFilePath = "copy_example.txt";

File.Copy(sourceFilePath, destinationFilePath);

五、LINQ查询

以下是一些涉及LINQ查询的代码片段,包括基本查询、排序、聚合等。

1. 基本查询

List numbers = new List { 1, 2, 3, 4, 5 };

var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (int number in evenNumbers)

{

Console.WriteLine(number);

}

2. 排序

List numbers = new List { 5, 2, 1, 4, 3 };

var sortedNumbers = numbers.OrderBy(n => n);

foreach (int number in sortedNumbers)

{

Console.WriteLine(number);

}

3. 聚合

List numbers = new List { 1, 2, 3, 4, 5 };

int sum = numbers.Sum();

Console.WriteLine($"Sum: {sum}");

六、网络编程

以下是一些涉及网络编程的代码片段,包括HTTP请求、TCP连接等。

1. HTTP请求

string url = "https://www.example.com";

using (var client = new WebClient())

{

string content = client.DownloadString(url);

Console.WriteLine(content);

}

2. TCP连接

string ipAddress = "127.0.0.1";

int port = 12345;

using (var tcpClient = new TcpClient(ipAddress, port))

{

using (var stream = tcpClient.GetStream())

{

byte[] buffer = new byte[1024];

int bytesRead = stream.Read(buffer, 0, buffer.Length);

string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);

Console.WriteLine(message);

}

}

七、其他实用代码片段

以下是一些其他实用的C#代码片段,涵盖了日期时间处理、正则表达式、异步编程等。

1. 日期时间处理

DateTime currentDate = DateTime.Now;

Console.WriteLine($"Current Date and Time: {currentDate}");

DateTime futureDate = currentDate.AddDays(10);

Console.WriteLine($"Future Date: {futureDate}");

2. 正则表达式

string input = "123-456-7890";

var match = Regex.Match(input, @"(\d{3})-(\d{3})-(\d{4})");

if (match.Success)

{

Console.WriteLine($"Area Code: {match.Groups[1]}");

Console.WriteLine($"Exchange Code: {match.Groups[2]}");

Console.WriteLine($"Subscriber Number: {match.Groups[3]}");

}

3. 异步编程

async Task LongRunningOperationAsync()

{

Console.WriteLine("Operation started.");

await Task.Delay(1000);

Console.WriteLine("Operation completed.");

}

await LongRunningOperationAsync();

以上是60个C#代码片段的简要介绍,涵盖了C#编程的各个方面。这些代码片段旨在帮助开发人员迅速解决常见问题,尽大概减少损耗开发高效。愿望这些代码片段对您有所帮助!


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发


热门