c#难点2
1.对象池的使用
就是先定义一系列的对象,用一个,调一个。
public class ObjectPool<T> where T : new()
{
private Queue<T> pool; // 用于存储对象的队列
private int maxSize; // 对象池的最大容量
// 构造函数
public ObjectPool(int maxSize)
{
this.maxSize = maxSize;
pool = new Queue<T>(maxSize);
InitializePool();
}
// 初始化对象池
private void InitializePool()
{
for (int i = 0; i < maxSize; i++)
{
pool.Enqueue(new T()); // 创建对象并加入池中
}
}
// 从池中获取对象
public T GetObject()
{
if (pool.Count > 0)
{
return pool.Dequeue(); // 如果池中有对象,直接返回
}
else
{
Console.WriteLine("Pool is empty, creating new object.");
return default(T);//用完了返回null
//return new T(); // 如果池为空,创建新对象
}
}
// 将对象归还到池中
public void ReturnObject(T obj)
{
if (pool.Count < maxSize)
{
pool.Enqueue(obj); // 如果池未满,归还对象
}
else
{
Console.WriteLine("Pool is full, discarding object.");
}
}
}
2.virtual的使用
父类方法有virtual,子类方法才可家override,但是子类方法其实不加override也可调用
3.CopyTo方法