Cast type to IDisposable - Why?

后端 未结 3 1296
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 13:28

Saw this. Why the explicit cast to IDisposable? Is this just a shorthand to ensure that IDisposable is called on exiting the using block?

using (proxy as IDi         


        
3条回答
  •  不思量自难忘°
    2020-12-31 13:59

    It's unnecessary as the using statement is explicitly tied to the IDisposable interface, per the MSDN docs

    Provides a convenient syntax that ensures the correct use of IDisposable objects.

    edit: The C# language spec (sec. 8.13) provides three possible expansions for the using statement's syntactic sugar:

    A using statement of the form

    using (ResourceType resource = expression) statement
    

    corresponds to one of three possible expansions. When ResourceType is a non-nullable value type, the expansion is

    {
       ResourceType resource = expression;
       try {
          statement;
       }
       finally {
          ((IDisposable)resource).Dispose();
       }
    }
    

    Otherwise, when ResourceType is a nullable value type or a reference type other than dynamic, the expansion is

    {
       ResourceType resource = expression;
       try {
          statement;
       }
       finally {
          if (resource != null) ((IDisposable)resource).Dispose();
       }
    }
    

    Otherwise, when ResourceType is dynamic, the expansion is

    {
       ResourceType resource = expression;
       IDisposable d = (IDisposable)resource;
       try {
          statement;
       }
       finally {
          if (d != null) d.Dispose();
       }
    }
    

    Note that in each one of these expansions the cast is done anyway, so as originally stated, the as IDisposable is unnecessary.

提交回复
热议问题