开发者

Why implement interface explicitly?

开发者 https://www.devze.com 2023-01-24 03:01 出处:网络
So, what exactly is a good use case for implementing an inte开发者_StackOverflowrface explicitly?

So, what exactly is a good use case for implementing an inte开发者_StackOverflowrface explicitly?

Is it only so that people using the class don't have to look at all those methods/properties in intellisense?


If you implement two interfaces, both with the same method and different implementations, then you have to implement explicitly.

public interface IDoItFast
{
    void Go();
}
public interface IDoItSlow
{
    void Go();
}
public class JustDoIt : IDoItFast, IDoItSlow
{
    void IDoItFast.Go()
    {
    }

    void IDoItSlow.Go()
    {
    }
}


It's useful to hide the non-preferred member. For instance, if you implement both IComparable<T> and IComparable it is usually nicer to hide the IComparable overload to not give people the impression that you can compare objects of different types. Similarly, some interfaces are not CLS-compliant, like IConvertible, so if you don't explicitly implement the interface, end users of languages that require CLS compliance cannot use your object. (Which would be very disastrous if the BCL implementers did not hide the IConvertible members of the primitives :))

Another interesting note is that normally using such a construct means that struct that explicitly implement an interface can only invoke them by boxing to the interface type. You can get around this by using generic constraints::

void SomeMethod<T>(T obj) where T:IConvertible

Will not box an int when you pass one to it.


Some additional reasons to implement an interface explicitly:

backwards compatibility: In case the ICloneable interface changes, implementing method class members don't have to change their method signatures.

cleaner code: there will be a compiler error if the Clone method is removed from ICloneable, however if you implement the method implicitly you can end up with unused 'orphaned' public methods

strong typing: To illustrate supercat's story with an example, this would be my preferred sample code, implementing ICloneable explicitly allows Clone() to be strongly typed when you call it directly as a MyObject instance member:

public class MyObject : ICloneable
{
  public MyObject Clone()
  {
    // my cloning logic;  
  }

  object ICloneable.Clone()
  {
    return this.Clone();
  }
}


Another useful technique is to have a function's public implementation of a method return a value which is more specific than specified in an interface.

For example, an object can implement ICloneable, but still have its publicly-visible Clone method return its own type.

Likewise, an IAutomobileFactory might have a Manufacture method which returns an Automobile, but a FordExplorerFactory, which implements IAutomobileFactory, might have its Manufacture method return a FordExplorer (which derives from Automobile). Code which knows that it has a FordExplorerFactory could use FordExplorer-specific properties on an object returned by a FordExplorerFactory without having to typecast, while code which merely knew that it had some type of IAutomobileFactory would simply deal with its return as an Automobile.


It's also useful when you have two interfaces with the same member name and signature, but want to change the behavior of it depending how it's used. (I don't recommend writing code like this):

interface Cat
{
    string Name {get;}
}

interface Dog
{
    string Name{get;}
}

public class Animal : Cat, Dog
{
    string Cat.Name
    {
        get
        {
            return "Cat";
        }
    }

    string Dog.Name
    {
        get
        {
            return "Dog";
        }
    }
}
static void Main(string[] args)
{
    Animal animal = new Animal();
    Cat cat = animal; //Note the use of the same instance of Animal. All we are doing is picking which interface implementation we want to use.
    Dog dog = animal;
    Console.WriteLine(cat.Name); //Prints Cat
    Console.WriteLine(dog.Name); //Prints Dog
}


It can keep the public interface cleaner to explicitly implement an interface, i.e. your File class might implement IDisposable explicitly and provide a public method Close() which might make more sense to a consumer than Dispose().

F# only offers explicit interface implementation so you always have to cast to the particular interface to access its functionality, which makes for a very explicit (no pun intended) use of the interface.


If you have an internal interface and you don't want to implement the members on your class publicly, you would implement them explicitly. Implicit implementations are required to be public.


Another reason for explicit implementation is for maintainability.

When a class gets "busy"--yes it happens, we don't all have the luxury of refactoring other team members' code--then having an explicit implementation makes it clear that a method is in there to satisfy an interface contract.

So it improves the code's "readability".


A different example is given by System.Collections.Immutable, in which the authors opted to use the technique to preserve a familiar API for collection types while scraping away the parts of the interface that carry no meaning for their new types.

Concretely, ImmutableList<T> implements IList<T> and thus ICollection<T> (in order to allow ImmutableList<T> to be used more easily with legacy code), yet void ICollection<T>.Add(T item) makes no sense for an ImmutableList<T>: since adding an element to an immutable list must not change the existing list, ImmutableList<T> also derives from IImmutableList<T> whose IImmutableList<T> Add(T item) can be used for immutable lists.

Thus in the case of Add, the implementations in ImmutableList<T> end up looking as follows:

public ImmutableList<T> Add(T item)
{
    // Create a new list with the added item
}

IImmutableList<T> IImmutableList<T>.Add(T value) => this.Add(value);

void ICollection<T>.Add(T item) => throw new NotSupportedException();

int IList.Add(object value) => throw new NotSupportedException();


In case of explicitly defined interfaces, all methods are automatically private, you can't give access modifier public to them. Suppose:

interface Iphone{

   void Money();

}

interface Ipen{

   void Price();
}


class Demo : Iphone, Ipen{

  void Iphone.Money(){    //it is private you can't give public               

      Console.WriteLine("You have no money");
  }

  void Ipen.Price(){    //it is private you can't give public

      Console.WriteLine("You have to paid 3$");
  }

}


// So you have to cast to call the method


    class Program
    {
        static void Main(string[] args)
        {
            Demo d = new Demo();

            Iphone i1 = (Iphone)d;

            i1.Money();

            ((Ipen)i1).Price();

            Console.ReadKey();
        }
    }

  // You can't call methods by direct class object


This is how we can create Explicit Interface: If we have 2 interface and both the interface have the same method and a single class inherit these 2 interfaces so when we call one interface method the compiler got confused which method to be called, so we can manage this problem using Explicit Interface. Here is one example i have given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace oops3
{
    interface I5
    {
        void getdata();    
    }
    interface I6
    {
        void getdata();    
    }

    class MyClass:I5,I6
    {
        void I5.getdata()
        {
           Console.WriteLine("I5 getdata called");
        }
        void I6.getdata()
        {
            Console.WriteLine("I6 getdata called");
        }
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            ((I5)obj).getdata();                     

            Console.ReadLine();    
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号