简体   繁体   中英

C#: Interface implementation

I found the following implementation in a code base I am going through

Interface IOrder
{
GetSubmittedOrder();
CreateOrder();
GetExistingOrder();
}

Class Order : IOrder
{
BuildSpecialOrder();
AddSpecialOrderParameters();
IOrder.GetSubmittedOrder();
IOrder.CreateOrder();
IOrder.GetExistingOrder();
}

Now, when we want to access the last three methods from this Order object, we need to do the following declaration

IOrder objOrder = new Order();

What is the reason(advantages) for creating an implementation like this? Does this practice have a specific name?

Note: Please let me know if this is a better fit at programmers.

Its called explicit interface implementation .

It is used to differentiate the implementation of specific interface in case multiple interface are implemented have the colliding names of methods.

interface IOrder
{
  GetSubmittedOrder();
  CreateOrder();
  GetExistingOrder();
}

interface ISpecificOrder
{
  GetSubmittedOrder();
  CreateOrder();
  GetExistingOrder();
}

Class Order : IOrder, ISpecificOrder
{
  BuildSpecialOrder();
  AddSpecialOrderParameters();

  IOrder.GetSubmittedOrder();
  IOrder.CreateOrder();
  IOrder.GetExistingOrder();

  ISpecificOrder.GetSubmittedOrder();
  ISpecificOrder.CreateOrder();
  ISpecificOrder.GetExistingOrder();

}

I would say that that's the incorrect usage of explicit interface implementation . It basically means that the methods are not visible in the public class contract. That's why you have to cast the object to the interface type first (you are using an implicit cast). You could also have done:

var order = (IOrder)order;
order.GetExistingOrder();

It's normally used when the class method collides with an interface method or when a class implements two interfaces with the same method (but different purposes).

It should be used with care since it can indicate that your class have a too large responsibility (and should be divided into smaller classes).

Consider adapter pattern Wiki - Adapter pattern
When communicating with other application or part of app (and many other requirements), you dont want to bind the type as it will be decided on run time, you can use this type of object declaration. this will create the object of interface type but will allocate memory of required type(nested in switch case or returned by other function).

 IOrder objOrder = new Order();

Another thing mentioned in question is about implicit and explicit implementation of interface. Both can be used in different scenario. You can find more details from google.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM