计算代码块执行时间
{
// 创建一个 Stopwatch 实例
Stopwatch stopwatch = new Stopwatch();
// 启动计时器
stopwatch.Start();
// 需要测量时间的代码段
PerformTask();
// 停止计时器
stopwatch.Stop();
// 获取代码段的执行时间
TimeSpan elapsedTime = stopwatch.Elapsed;
// 输出执行时间
Console.WriteLine("代码段执行时间: " + elapsedTime.TotalMilliseconds + " 毫秒");
}
List分批处理
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 示例 List
List<int> dataList = new List<int>();
// 假设 dataList 已经被填充数据
int batchSize = 10000;
int totalCount = dataList.Count;
for (int i = 0; i < totalCount; i += batchSize)
{
int currentBatchSize = Math.Min(batchSize, totalCount - i);
List<int> batch = dataList.GetRange(i, currentBatchSize);
// 处理当前批次数据
ProcessBatch(batch);
}
}
static void ProcessBatch(List<int> batch)
{
// 处理批次数据的逻辑
Console.WriteLine($"Processing batch of size: {batch.Count}");
}
}
使用属性和递归实现自定义类的深拷贝
public static T DeepCopy<T>(T obj)
{
// 如果传入值为空,直接返回。
if (obj == null)
return obj;
// 获取obj类型。
Type type = obj.GetType();
// 使用传入值类型的无参数构造函数创建该类型的实例。
var copy = Activator.CreateInstance(typeof(T), nonPublic: true);
// 获取传入值的所有属性。
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object? value = property.GetValue(obj);
if (value != null)
{
if (property.PropertyType.IsValueType || property.PropertyType == typeof(string))
{
// 属性为基础类型或string,拷贝。
property.SetValue(copy, value);
}
else
{
// 属性为引用类型,递归调用深拷贝。
property.SetValue(copy, DeepCopy(value));
}
}
}
}
return (T)copy!;
}
使用属性和递归实现自定义类的值比较
public static bool CompareObjects<T>(T obj1, T obj2)
{
if (obj1 == null && obj2 == null)
return true;
if (obj1 == null || obj2 == null)
return false;
Type type1 = obj1.GetType();
Type type2 = obj2.GetType();
if (type1 != type2)
return false;
PropertyInfo[] properties = type1.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object? value1 = property.GetValue(obj1);
object? value2 = property.GetValue(obj2);
if (value1 != null && value2 != null)
{
if (property.PropertyType.IsValueType || property.PropertyType == typeof(string))
{
if (!value1.Equals(value2))
{
return false;
}
}
else
{
CompareObjects(value1, value2);
}
}
else if (value1 == null && value2 == null)
{
continue;
}
else
{
return false;
}
}
}
return true;
}