ClientBase doesn't implement IDisposable member

前端 未结 3 1318
旧巷少年郎
旧巷少年郎 2021-02-20 14:08

How is it possible for the System.ServiceModel.ClientBase abstract class to implement IDisposable Interface if the Dispose() Method declaration is not visible/declared?

相关标签:
3条回答
  • 2021-02-20 14:09

    ClientBase<TChannel> implements IDisposable using explicit interface implementation.

    The implementation for this just calls close:

    void IDisposable.Dispose()
    {
        this.Close();
    }
    
    0 讨论(0)
  • 2021-02-20 14:24

    As pretty much everyone has pointed out, the interface method is explicitly implemented. The source code you are seeing for ClientBase<TChannel> is from Metadata (see Metadata as Source in Visual Studio). Note the lack of implementation for any function or a partial keyword.

    Visual Studio will not show explicitly implemented interface members from Metadata (see Stack Overflow question 72686320)


    Edit:

    An explicitly implemented interface method must be called from the interface directly (this is how it differs from one that was implemented implicitly). The correct way to call it is as follows

    using System;
    
    abstract class ATest : IDisposable
    {
        void IDisposable.Dispose()
        {
            throw new NotImplementedException();
        }
    }
    
    class Test : ATest
    {
    }
    
    class OtherClass
    {
        public static void Main()
        {
            Test t = new Test();
            ((IDisposable)t).Dispose();
        }
    }
    

    The result is Unhandled Exception: System.NotImplementedException: The requested feature is not implemented.

    0 讨论(0)
  • 2021-02-20 14:25

    using explicit interface implementation.

    IDisposable is visible and can be invoked as

    var client = new WCFTestServiceClient(); // assumingWCFTestServiceClient is WCF client proxy that inherits from ClientBase
    (client as IDisposable).Dispose();
    
    0 讨论(0)
提交回复
热议问题