Csharp代码大全
在前几期中推荐了Dotnet需要掌握的知识技能大全传送门, 或者访问 Dotnet知识技能大全 : https://www.dotnetshare.com/article/dotnetskill.html
今天总结了一下Csharp中超有用的代码大全,从入门进阶到高级包含了一下代码示例 基础语法、数据类型、条件判断、循环、数组、方法、面向对象、继承、接口、抽象类、多态、封装、静态变量、内部类、匿名类、泛型、集合框架、异常处理、文件I/O、多线程、同步、高级多线程概念、事件和委托、Lambda表达式、表达式树、可空值类型、动态类型、反射、序列化和反序列化、单元测试、内存映射文件、正则表达式、异步流、模式匹配、记录类型、顶级语句、目标类型的新语法、只读属性、接口的默认实现、表达式-bodied成员、属性的只读结构、局部函数、可空引用类型、模块初始化器、全局using指令、文件范围的using声明、隐藏实现的成员、静态抽象成员、目标类型的new表达式、记录类型的with表达式、模式匹配的switch表达式、异步流。
- 基础语法:包括使用声明、命名空间和程序入口点的定义。
- 数据类型:涉及 C# 中的基本数据类型,例如 bool、byte、sbyte、short、int、long、float、double、decimal、char 和 string。
- 条件判断:展示了如何使用 if-else 语句进行条件判断。
- 循环:包括 for 循环和 foreach 循环的使用。
- 数组:介绍了一维和二维数组的声明和访问。
- 方法:展示了如何定义和调用方法。
- 面向对象:包括类的定义、属性和方法的使用。
- 继承:展示了如何通过继承扩展类的功能。
- 接口:介绍了接口的定义和实现。
- 抽象类:展示了如何定义抽象类和抽象方法。
- 多态:展示了如何通过重写实现多态性。
- 封装:通过私有成员和公共访问器展示封装的概念。
- 静态变量:展示了静态成员的使用。
- 内部类:展示了如何定义和使用内部类。
- 匿名类:介绍了匿名类型的定义和使用。
- 泛型:展示了泛型类和方法的使用。
- 集合框架:介绍了 List 和 Dictionary 等集合类型的使用。
- 异常处理:展示了 try、catch 和 finally 语句的使用。
- 文件 I/O:包括文件的读写操作。
- 文件目录操作:包括目录的创建、移动、删除和遍历等操作。
- 多线程:介绍了线程的创建和同步。
- 同步:展示了如何使用锁确保线程安全。
- 高级多线程概念:包括 Parallel 类的使用和异步编程。
- 事件和委托:介绍了事件的发布和订阅机制。
- Lambda 表达式:展示了 Lambda 表达式的使用。
- 表达式树:介绍了表达式树的概念和使用。
- 可空值类型:展示了可空值类型的使用。
- 动态类型:展示了动态类型的使用。
- 反射:介绍了反射机制的使用。
- 序列化和反序列化:展示了对象的序列化和反序列化过程。
- 单元测试:介绍了使用 NUnit 进行单元测试的方法。
- 内存映射文件:展示了内存映射文件的使用。
- 正则表达式:介绍了正则表达式的使用。
- 异步流:展示了异步流的创建和使用。
- 模式匹配:介绍了模式匹配的概念和使用。
- 记录类型:展示了 C# 9.0 引入的记录类型的使用。
- 顶级语句:介绍了 C# 9.0 引入的顶级语句的概念。
- 目标类型的新语法:展示了 C# 9.0 引入的目标类型初始化的语法。
- 只读属性:展示了 C# 9.0 引入的只读属性的使用。
- 接口的默认实现:介绍了 C# 8.0 引入的接口默认实现。
- 表达式-bodied成员:展示了 C# 6.0 引入的表达式-bodied成员。
- 属性的只读结构:展示了 C# 7.2 引入的只读结构的使用。
- 局部函数:介绍了 C# 7.0 引入的局部函数的概念。
- 可空引用类型:再次提到了 C# 8.0 引入的可空引用类型。
- 模块初始化器:介绍了 C# 10.0 引入的模块初始化器。
- 全局using指令:介绍了 C# 10.0 引入的全局using指令。
- 文件范围的using声明:介绍了 C# 10.0 引入的文件范围的命名空间声明。
- 隐藏实现的成员:介绍了 C# 10.0 引入的隐藏实现的成员。
- 静态抽象成员:展示了 C# 9.0 引入的静态抽象成员的使用。
- 目标类型的new表达式:再次提到了 C# 9.0 引入的目标类型初始化的语法。
- 记录类型的with表达式:再次提到了 C# 9.0 引入的记录类型 with 表达式。
- 模式匹配的switch表达式:介绍了 C# 8.0 引入的模式匹配 switch 表达式。
- 异步流:再次提到了 C# 9.0 引入的异步流。
基础语法
using System;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, C#!");
}
}
}
数据类型
bool isTrue = true;
byte myByte = 255;
sbyte mySByte = -128;
short myShort = 32767;
int myInt = 2147483647;
long myLong = 9223372036854775807;
float myFloat = 3.40282e+38F;
double myDouble = 1.7976931348623157E+308;
decimal myDecimal = 7.92281625e+28;
char myChar = 'A';
string myString = "Hello";
条件判断
int number = 5;
if (number < 10)
{
Console.WriteLine("The number is less than 10.");
}
else
{
Console.WriteLine("The number is greater than or equal to 10.");
}
循环
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
数组
int[] myArray = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine(myArray[2]); // Outputs 3
int[,] my2DArray = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Console.WriteLine(my2DArray[2, 1]); // Outputs 6
方法
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(5, 10);
Console.WriteLine(result); // Outputs 15
}
面向对象
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
static void Main()
{
Person person = new Person { Name = "Alice", Age = 30 };
person.Introduce();
}
继承
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
static void Main()
{
Dog myDog = new Dog();
myDog.Eat(); // Inherited method
myDog.Bark(); // Dog specific method
}
接口
public interface IShape
{
double Area();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double Area()
{
return Math.PI * Radius * Radius;
}
}
static void Main()
{
IShape myShape = new Circle { Radius = 5 };
Console.WriteLine(myShape.Area());
}
抽象类
public abstract class Shape
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width * Height;
}
}
static void Main()
{
Shape myShape = new Rectangle { Width = 5, Height = 10 };
Console.WriteLine(myShape.Area());
}
多态
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
static void AnimalSound(Animal animal)
{
animal.MakeSound();
}
static void Main()
{
Animal myAnimal = new Animal();
Animal myDog = new Dog();
AnimalSound(myAnimal); // Outputs "Some sound"
AnimalSound(myDog); // Outputs "Bark"
}
封装
public class BankAccount
{
private decimal _balance;
public decimal Balance
{
get { return _balance; }
private set { _balance = value; }
}
public void Deposit(decimal amount)
{
_balance += amount;
}
public void Withdraw(decimal amount)
{
if (_balance >= amount)
{
_balance -= amount;
}
}
}
静态变量
public class MathUtils
{
public static double Pi = 3.14159;
public static double AreaOfCircle(double radius)
{
return Pi * radius * radius;
}
}
static void Main()
{
double area = MathUtils.AreaOfCircle(5);
Console.WriteLine(area);
}
内部类
public class OuterClass
{
public class InnerClass
{
public void Print()
{
Console.WriteLine("Inner class");
}
}
}
static void Main()
{
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.Print();
}
匿名类
var person = new
{
Name = "John Doe",
Age = 30
};
Console.WriteLine(person.Name);
泛型
public class GenericList<T>
{
private List<T> _items = new List<T>();
public void Add(T item)
{
_items.Add(item);
}
public T Get(int index)
{
return _items[index];
}
}
static void Main()
{
GenericList<int> intList = new GenericList<int>();
intList.Add(1);
intList.Add(2);
Console.WriteLine(intList.Get(0)); // Outputs 1
}
集合框架
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6);
int lastNumber = numbers.Last();
Console.WriteLine(lastNumber); // Outputs 6
Dictionary<string, int> scores = new Dictionary<string, int>
{
{ "Alice", 90 },
{ "Bob", 85 }
};
scores["Alice"] = 95;
Console.WriteLine(scores["Alice"]); // Outputs 95
异常处理
try
{
int result = 10 / 0; // Division by zero
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
Console.WriteLine("This will always be executed.");
}
文件I/O
string path = "example.txt";
string textToWrite = "Hello, World!";
// Writing to a file
System.IO.File.WriteAllText(path, textToWrite);
// Reading from a file
string fileContent = System.IO.File.ReadAllText(path);
Console.WriteLine(fileContent);
文件目录操作
//创建目录
Directory.CreateDirectory("newDirectory");
//获取目录下所有文件和子目录
var files = Directory.GetFiles("directoryPath");
var subDirectories = Directory.GetDirectories("directoryPath");
//移动目录
Directory.Move("sourcePath", "destinationPath");
//删除目录及其内容
Directory.Delete("directoryPath", true);
//获取目录信息
var di = new DirectoryInfo("directoryPath");
Console.WriteLine(di.CreationTime);
//遍历目录树
void TraverseDirectory(DirectoryInfo di)
{
foreach (FileInfo fi in di.EnumerateFiles())
{
Console.WriteLine(fi.Name);
}
foreach (DirectoryInfo subDi in di.EnumerateDirectories())
{
TraverseDirectory(subDi);
}
}
多线程
Thread thread = new Thread(() => Console.WriteLine("Hello from a new thread!"));
thread.Start();
thread.Join(); // Wait for the thread to finish
同步
object lockObject = new object();
void ThreadSafeMethod()
{
lock (lockObject)
{
// Code that needs to be thread-safe
}
}
高级多线程概念
// Using Parallel class for parallel loop
Parallel.For(0, 10, i =>
{
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}, i: {i}");
});
异步编程(Async/Await)
using System;
using System.Threading.Tasks;
public class AsyncDemo
{
public async Task DoAsyncWork()
{
await Task.Delay(1000); // Simulate work with async delay
Console.WriteLine("Work completed asynchronously.");
}
}
static async Task Main()
{
var demo = new AsyncDemo();
await demo.DoAsyncWork();
Console.WriteLine("Main thread continues after async work.");
}
事件和委托
using System;
public delegate void MessageEventHandler(object sender, MessageEventArgs e);
public class MessageEventArgs : EventArgs
{
public string Message { get; set; }
}
public class Publisher
{
public event MessageEventHandler MessageReceived;
protected virtual void OnMessageReceived(MessageEventArgs e)
{
MessageReceived?.Invoke(this, e);
}
public void Send(string message)
{
OnMessageReceived(new MessageEventArgs { Message = message });
}
}
public class Subscriber
{
public Subscriber(Publisher publisher)
{
publisher.MessageReceived += OnMessageReceived;
}
private void OnMessageReceived(object sender, MessageEventArgs e)
{
Console.WriteLine($"Received message: {e.Message}");
}
}
static void Main()
{
var publisher = new Publisher();
var subscriber = new Subscriber(publisher);
publisher.Send("Hello, World!");
}
Lambda表达式
using System;
public class LambdaDemo
{
public void Process(int[] numbers, Func<int, bool> condition)
{
foreach (var number in numbers)
{
if (condition(number))
{
Console.WriteLine(number);
}
}
}
}
static void Main()
{
var demo = new LambdaDemo();
demo.Process(new[] { 1, 2, 3, 4, 5 }, x => x % 2 == 0);
}
表达式树
using System;
using System.Linq.Expressions;
public class ExpressionTreeDemo
{
public void PrintExpressionTree()
{
Expression<Func<int, int, int>> expression = (a, b) => a + b;
Console.WriteLine(expression.Body); // Outputs: a + b
}
}
static void Main()
{
var demo = new ExpressionTreeDemo();
demo.PrintExpressionTree();
}
可空值类型(Nullable Value Types)
int? nullableInt = null;
if (nullableInt.HasValue)
{
Console.WriteLine(nullableInt.Value);
}
else
{
Console.WriteLine("Value is null");
}
动态类型
dynamic d = 10;
d += " is greater than 5";
Console.WriteLine(d); // Outputs: 10 is greater than 5
反射
using System;
using System.Reflection;
public class ReflectionDemo
{
public void PrintProperties()
{
PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine($"{property.Name} is of type {property.PropertyType}");
}
}
}
static void Main()
{
ReflectionDemo demo = new ReflectionDemo();
demo.PrintProperties();
}
序列化和反序列化
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
static void Main()
{
Person person = new Person { Name = "John Doe", Age = 30 };
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream("person.dat", FileMode.Create))
{
formatter.Serialize(stream, person);
}
using (FileStream stream = new FileStream("person.dat", FileMode.Open))
{
Person deserializedPerson = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
单元测试(使用NUnit)
using NUnit.Framework;
[TestFixture]
public class CalculatorTests
{
private Calculator _calculator;
[SetUp]
public void SetUp()
{
_calculator = new Calculator();
}
[Test]
public void Add_ValidNumbers_ReturnsSum()
{
// Arrange
int a = 5;
int b = 10;
// Act
int result = _calculator.Add(a, b);
// Assert
Assert.AreEqual(15, result);
}
}
public class Calculator
{
public int Add(int x, int y)
{
return x + y;
}
}
内存映射文件
using System;
using System.IO.MemoryMappedFiles;
public class MemoryMappedFileDemo
{
public void CreateAndAccess()
{
using (var mmf = MemoryMappedFile.CreateNew("MyMapFile", 1024))
{
using (var accessor = mmf.CreateViewAccessor())
{
accessor.Write(0, 100);
int value = accessor.ReadInt32(0);
Console.WriteLine(value); // Outputs: 100
}
}
}
}
static void Main()
{
var demo = new MemoryMappedFileDemo();
demo.CreateAndAccess();
}
正则表达式
using System;
using System.Text.RegularExpressions;
public class RegexDemo
{
public void MatchPattern()
{
string pattern = @"\b[A-Za-z]+\b";
string input = "Hello, this is a test.";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
static void Main()
{
var demo = new RegexDemo();
demo.MatchPattern();
}
异步流(C# 8.0 引入)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
public class AsyncStreamsDemo
{
public async IAsyncEnumerable<int> GenerateNumbers()
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(100); // Simulate work
yield return i;
}
}
}
static async Task Main()
{
var demo = new AsyncStreamsDemo();
await foreach (var number in demo.GenerateNumbers())
{
Console.WriteLine(number);
}
}
模式匹配(Pattern Matching)
public class PatternMatchingDemo
{
public void Process(object obj)
{
switch (obj)
{
case int i:
Console.WriteLine($"Integer: {i}");
break;
case string s when s.Length > 10:
Console.WriteLine($"Long string: {s}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
default:
Console.WriteLine("Unknown type");
break;
}
}
}
static void Main()
{
var demo = new PatternMatchingDemo();
demo.Process("Hello, World!");
demo.Process(123);
demo.Process("A very long string that is more than ten characters long.");
}
记录类型(Record Types,C# 9.0 引入)
public record Person(string Name, int Age);
static void Main()
{
var person = new Person("Alice", 30);
Console.WriteLine(person);
var anotherPerson = person with { Name = "Bob" };
Console.WriteLine(anotherPerson);
}
顶级语句(Top-Level Statements,C# 9.0 引入)
// This is a script file, not a class. No class or namespace required.
Console.WriteLine("Hello, C# script!");
int number = 5;
Console.WriteLine($"The number is {number}");
目标类型的新语法(Target-typed new,C# 9.0 引入)
public class Product
{
public string Name { get; init; }
public decimal Price { get; init; }
}
static void Main()
{
var product = new Product { Name = "Apple", Price = 0.99m };
Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
}
只读属性(Read-Only Properties,C# 9.0 引入)
public class Rectangle
{
public double Width { get; }
public double Height { get; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public double Area => Width * Height;
}
static void Main()
{
var rectangle = new Rectangle(5, 10);
Console.WriteLine($"Area: {rectangle.Area}");
}
接口的默认实现(Default Interface Implementations,C# 8.0 引入)
public interface IShape
{
double Area { get; }
void Draw(); // 默认实现
}
public interface IDrawable : IShape
{
void Fill();
}
public class Circle : IDrawable
{
public double Radius { get; }
public Circle(double radius)
{
Radius = radius;
}
public double Area => Math.PI * Radius * Radius;
public void Draw() => Console.WriteLine("Drawing a circle.");
public void Fill() => Console.WriteLine("Filling the circle.");
}
static void Main()
{
var circle = new Circle(5);
circle.Draw(); // 使用接口的默认实现
circle.Fill();
}
因篇幅有限,更多代码请在在线网站查看,或者点击文件底部的阅读全文