Can I safely clear the readonly field field?

Say I have a class with an object field. When Dispose () is called, I would like to clear the reference to this object. A private field can only be set once, so ideally I would like it to be read-only, but if it is read-only, a compile-time error occurs when I try to release a reference to an object during Dispose (). Ideally, I would like to have a secure AND utility and mark the _value field as readonly. Is this possible or even necessary?

public class Foo : IDisposable
{
      public Foo(object value)
      {
            _value = value;
      }

      public object Value { get { return _value; } }
      private readonly object _value;

      public void Dispose()
      {
            //Cleanup here
            _value = null     // causes compile time error
      }
}
+3
source share
4 answers

This is not necessary, even if it was possible.

Dispose , ( ). . , . , . , .

+2

null . , , , Dispose, , Foo , , , . , Dispose, , IDisposable ( Object, IDisposable), , . Dispose . : - , IDisposable, Dispose Dispose:

public class SomeClass : IDisposable
{
    private Boolean mDisposed;
    private readonly MemoryStream mStream = new MemoryStream(); // Could be any class that implements IDisposable
    public void Dispose() {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected void Dispose(Boolean disposing) {
        if (disposing & !mDisposed) {
            mStream.Dispose();  // Could and should call Dispose
            mDisposed = true;
        }
        return;
    }
}

, readonly , .

+3

. , , , , - , .

, , , , , IsDisposed ( btw Dispose) .

, Dispose .

+1

, , , .

, , , , , , .

, , , . "readonly", , , . , , , .

0

Source: https://habr.com/ru/post/1770847/


All Articles