c# - 处理对象时避免重复编码

标签 c# repository-pattern dispose non-repetitive

出于内存优化的目的,我们一直在添加这些代码行:

public class Whatever: IDisposable

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
    if (!this.disposed)
    {
        if (disposing)
        {
            context.Dispose();
        }
    }
    this.disposed = true;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

对于我们的每一个存储库,然后也在为每个存储库更新测试。 我想知道,既然在编码中并不真正鼓励复制+粘贴,难道没有更好的方法来实现它吗?特别烦人,因为根据项目的不同,我们有 10-40 个存储库......

最佳答案

也许更简单 - 使用 context 本身来跟踪处置:

protected virtual void Dispose(bool disposing)
{
    if (disposing) context?.Dispose();
    context = null;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

请注意,我还认为您完全不太可能在此处涉及终结器(如果您这样做,那可能是一个大错误),所以老实说:您可以进一步简化:

public void Dispose()
{
    context?.Dispose();
    context = null;
}

关于c# - 处理对象时避免重复编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69221484/

相关文章:

C# 为什么其中一些使用委托(delegate)和泛型的方法没有启动?

.net - Asp Net Mvc 中的 SOLID 原理、Repository 模式和 EntityFramework 缓存

.net - 存储库模式是否过大?

c# - 为什么推荐的 dispose 模式会在层次结构的每个级别添加一个已处理字段?

c# - 在什么时候我需要处理我的自定义 WPF 用户控件?

c# Double.MinValue 和 Double.MaxValue 之间的随机数

c# - Context.UpdateObject() 不传递对象中的集合

c# - 获取方法的集合

domain-driven-design - 如何处理在 DDD w/Clean Architecture 中具有太多依赖参数的 UseCase Interactor 构造函数?

c# - 通过引用传递 IDisposable 对象会导致错误?