C# 如何处置属于另一个类的属性的类?
在DC是服务类属性的情况下,如何处理DCC# 如何处置属于另一个类的属性的类?,c#,C#,在DC是服务类属性的情况下,如何处理DC class Service() { public DataContext DC= new DataContext(); public void SomeMethod() { DC is used here. } public void SomeOtherMethod() { DC is also used here.
class Service()
{
public DataContext DC= new DataContext();
public void SomeMethod()
{
DC is used here.
}
public void SomeOtherMethod()
{
DC is also used here.
}
}
如果“服务”类维护对非托管资源的引用,那么它应该实现IDisposable。这会告诉类的客户端他们需要对“服务”的实例调用Dispose()。您可以在类的Dispose()方法中对“DC”调用Dispose()
另一方面,我会避免在C#中创建公共字段,其中属性是常见的习惯用法。使您的服务IDisposable,并在dispose方法中处理DataContext。这是一种常见的模式。您可以在宿主类上实现,并在dispose()方法中处置托管的DC。然后使用“using”使用宿主类
using(Service service = new Service())
{
// do something with "service" here
}
您的服务类应该负责处理DataContext 使用标准。实现IDisposable:
服务实例本身呢?我是否需要向Dispose方法添加更多内容,或者GC是否像往常一样工作?垃圾收集器完全能够处理托管类,您只需要调用Dispose来清理任何非托管资源。
using(Service service = new Service())
{
// do something with "service" here
}
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (DC != null)
DC.Dispose();
}
// Indicate that the instance has been disposed.
DC = null;
_disposed = true;
}
}