c# - 为所有对象创建一个委托(delegate),而不是为每个对象创建一个委托(delegate)

标签 c# delegates

我有一个对象池,每当我对池中的对象调用 Free() 时,我都需要调用委托(delegate)方法 OnFree()。

Free() 是在外部创建的,并在创建池时在对象上设置。 OnFree 因对象而异,有时甚至为 null。

池中的对象继承自 Poolable 类。

class Poolable
{
    public Action Free();
    public Action OnFree();
}

目前,我通过这样做在继承类中创建 OnFree:

class Light
{
    public Light()
    {
        // Create method to be called when Free() is called on this light.
        OnFree = () =>
        {
            DoStuffHere();
        };
    }
}

但是,这将为每个灯光创建一个单独的委托(delegate),这会浪费大量内存,特别是当池中有数万个对象时。呃,每次调用这个构造函数时它都会创建一个新的委托(delegate),对吗?

什么是允许对象创建自己的 OnFree() 委托(delegate)的好方法,以便每个对象类型只有一个委托(delegate),而不是每个实例一个委托(delegate)?

我当然可以想到一种方法,但我希望有人能想到一种“好”方法——易于维护的方法。


编辑:我可以在基类中使 OnFree() 委托(delegate)静态,以便它以某种方式在每个继承类型中都是静态的吗?


编辑:澄清如何使用 Pool,以及为什么 Free() 是委托(delegate),而不是虚拟方法。如果您能想到更好的方法来做到这一点,请告诉我。

public class Pool<T> where T : Poolable
{
    private int _liveCount;
    private T[] _pool;
    [...]
    public Pool(int capacity, Func<T> allocateFunction)
    {
        [...]
        // Fill pool with initial items:
        for (int i = 0; i < capacity; i++)
        {
            T item = _allocate();
            item.Free = () => Free(item);
            _pool[i] = item;
        }
    }

    /// <summary>
    /// Frees given object from this pool. Object is assumed to
    /// be in this pool.
    /// </summary>
    public void Free(Poolable obj)
    {
        obj.OnFree();

        _liveCount -= 1;
        [...]
    }
}

最佳答案

如何保持简单:

class Poolable
{
    public virtual void Free() { }
    public virtual void OnFree() { }  // naming not according to BCL std
}

class Light : Poolable
{
    public override void Free() { }
    ...
}
  • 您的示例表明不需要委托(delegate)(通过虚拟方法)
  • 正确的封装需要事件而不是公共(public)委托(delegate)
  • 看来您的优化过早。

关于c# - 为所有对象创建一个委托(delegate),而不是为每个对象创建一个委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5924342/

相关文章:

c# - 学习 C# 和 .NET 的书籍

c# - LINQ to SQL 和编译查询

c# - GetHashCodes - 如何以及何时使用它?

c# - 如何在 C# 类库中编写异步方法

.net - 如何序列化指向被覆盖的虚拟方法基础的委托(delegate)?

c# - Try-catch until success - 通用方法或委托(delegate)的执行循环

c# - 动态构建 Azure DocumentDB 查询

c# - MySql.Data.MySqlClient 调用存储过程时出错

iphone - 如何在 TabbarController 中设置 viewControllers 的委托(delegate)?

objective-c - cocoa 教程麻烦