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

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

60个实用C#代码片段:每位开发者必备

一、基础语法

以下是一些C#基础语法相关的代码片段,涵盖了变量声明、数据类型转换等。

1. 变量声明

int number = 10;

string name = "张三";

float pi = 3.14f;

bool isTrue = true;

2. 数据类型转换

int num = 10;

float f = (float)num;

string str = num.ToString();

二、控制结构

以下是涉及C#控制结构的代码片段,包括条件语句、循环语句等。

1. if语句

int a = 5;

int b = 10;

if (a > b)

{

Console.WriteLine("a 大于 b");

}

else if (a < b)

{

Console.WriteLine("a 小于 b");

}

else

{

Console.WriteLine("a 等于 b");

}

2. for循环

for (int i = 0; i < 10; i++)

{

Console.WriteLine("i的值:" + i);

}

三、面向对象编程

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

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 SayHello()

{

Console.WriteLine("Hello, my name is " + Name);

}

}

Person person = new Person("张三", 25);

person.SayHello();

2. 继承与多态

public class Student : Person

{

public string School { get; set; }

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

{

School = school;

}

public void Study()

{

Console.WriteLine("我在" + School + "学习");

}

}

Student student = new Student("李四", 20, "清华大学");

student.SayHello();

student.Study();

四、集合与泛型

以下是涉及C#集合与泛型的代码片段,包括List、Dictionary、泛型方法等。

1. List的使用

List numbers = new List();

numbers.Add(1);

numbers.Add(2);

numbers.Add(3);

foreach (int number in numbers)

{

Console.WriteLine(number);

}

2. Dictionary的使用

Dictionary dictionary = new Dictionary();

dictionary.Add(1, "张三");

dictionary.Add(2, "李四");

foreach (KeyValuePair pair in dictionary)

{

Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);

}

五、文件操作

以下是涉及C#文件操作的代码片段,包括文件的读写、文件路径操作等。

1. 文件读取

string filePath = "example.txt";

using (StreamReader reader = new StreamReader(filePath))

{

string line;

while ((line = reader.ReadLine()) != null)

{

Console.WriteLine(line);

}

}

2. 文件写入

string filePath = "example.txt";

using (StreamWriter writer = new StreamWriter(filePath))

{

writer.WriteLine("Hello, World!");

}

六、LINQ查询

以下是涉及C# LINQ查询的代码片段,包括基本查询、聚合函数等。

1. 基本查询

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

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

foreach (var number in evenNumbers)

{

Console.WriteLine(number);

}

2. 聚合函数

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

int sum = numbers.Sum();

Console.WriteLine("总和:" + sum);

七、异步编程

以下是涉及C#异步编程的代码片段,包括Task、async和await关键字等。

1. 异步方法

public async Task CalculateSumAsync()

{

long sum = 0;

for (int i = 0; i < 100000000; i++)

{

sum += i;

}

return sum;

}

long result = await CalculateSumAsync();

Console.WriteLine("计算最终:" + result);

2. 异步事件

public delegate Task AsyncEvent();

public event AsyncEvent OnComplete;

public async Task PerformTaskAsync()

{

// 执行异步任务

await Task.Delay(1000);

// 触发异步事件

OnComplete?.Invoke();

}

OnComplete += () => Console.WriteLine("任务完成");

PerformTaskAsync();

八、网络编程

以下是涉及C#网络编程的代码片段,包括HTTP请求、TCP通信等。

1. HTTP请求

using (HttpClient client = new HttpClient())

{

string url = "https://api.example.com/data";

HttpResponseMessage response = await client.GetAsync(url);

string result = await response.Content.ReadAsStringAsync();

Console.WriteLine(result);

}

2. TCP通信

public void ConnectToServer(string ip, int port)

{

TcpClient client = new TcpClient(ip, port);

NetworkStream stream = client.GetStream();

// 发送数据

byte[] buffer = Encoding.ASCII.GetBytes("Hello, World!");

stream.Write(buffer, 0, buffer.Length);

// 接收数据

buffer = new byte[1024];

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

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

Console.WriteLine(received);

stream.Close();

client.Close();

}

九、单元测试

以下是涉及C#单元测试的代码片段,包括NUnit框架的使用。

1. NUnit测试类

using NUnit.Framework;

[TestFixture]

public class CalculatorTests

{

[Test]

public void AddTest()

{

int result = Calculator.Add(1, 2);

Assert.AreEqual(3, result);

}

[Test]

public void SubtractTest()

{

int result = Calculator.Subtract(5, 3);

Assert.AreEqual(2, result);

}

}

2. 测试方法

public static class Calculator

{

public static int Add(int a, int b)

{

return a + b;

}

public static int Subtract(int a, int b)

{

return a - b;

}

}

十、其他实用代码片段

以下是一些其他实用的C#代码片段,涵盖了字符串操作、日期时间处理等。

1. 字符串反转

public static string ReverseString(string input)

{

char[] charArray = input.ToCharArray();

Array.Reverse(charArray);

return new string(charArray);

}

2. 日期时间格式化

DateTime now = DateTime.Now;

string formattedDate = now.ToString("yyyy-MM-dd HH:mm:ss");

Console.WriteLine(formattedDate);

3. 随机数生成

Random random = new Random();

int randomNumber = random.Next(1, 100);

Console.WriteLine(randomNumber);

4. 获取IP地址

string ipAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();

Console.WriteLine(ipAddress);

5. 获取CPU核心数

int coreCount = Environment.ProcessorCount;

Console.WriteLine("CPU核心数:" + coreCount);

总结

以上是60个实用的C#代码片段,涵盖了C#编程的各个方面。掌握这些代码片段,将帮助您在开发过程中更加高效地解决问题。期望这篇文章对您有所帮助!


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

文章标签: 后端开发


热门