Reasons for clear implementation of Interface members



  • Schildt describes two reasons for the obvious implementation of the interface members, but I don't understand one of them. This is what he says: when the interface method is carried out with its full name, it is available not through the object of the class that operates the interface but through the interface. Therefore, clear implementation enables the use of the interface method in such a way that it does not become an open member of the class that provides it. I don't understand the meaning of the description and the reason why it should be used? The book gives the following example, so I have commented that I also don't understand the code:

    interface IEven { 
          bool IsOdd(int x); 
          bool IsEven(int x); 
        }
    
    class MyClass : IEven {
    
      bool IEven.IsOdd(int x) { 
        if((x%2) != 0) return true; 
        else return false; 
      }
    
      // Normal implementation. 
      public bool IsEven(int x) { 
        IEven o = this; //объясните данный участок кода
    
        return !o.IsOdd(x); 
      } 
    }
    
    class Demo { 
      static void Main() { 
        MyClass ob = new MyClass(); 
        bool result;
    
        result = ob.IsEven(4); 
        if(result) Console.WriteLine("4 is even.");
    
        // result = ob.IsOdd(4); // Error, IsOdd not exposed.
    
        IEven iRef = (IEven) ob; // объясните данный участок кода
        result = iRef.IsOdd(3); 
        if(result) Console.WriteLine("3 is odd."); 
    }
    



  • In general, it is necessary to do so when the challenge of the interface is not directly foreseen in the facility. For example, this method needs your interior infrastructure, and the application software player who uses your should not know about it.

    The second case is if the interface is not fully implemented. For example, class ControlCollection Implemented IListin which the method is announced Insertbut the method itself does not. So that the applied software player doesn't have the temptation to call him, the method is so hidden. If you try to call him, bring him a copy. ControlCollection to IList, method dropping NotSupportedException

    Another rather typical use of the obvious implementation of the interface is when the class runs a few interfaces whose members conflict by name. For example, all standard collections in .NET Do what they do. ICollectionand ICollection<T>♪ Most members ICollection It is clear that these classes clear.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2