简体   繁体   中英

what is the difference between explicit and implicit interface implementation in c#

what is the difference between explicit interface and implicit interface implementation in c#/asp.net? in which scenario we can use the explicit interface and implicit interface implementation.

Thanks,

Pradeep

The concept behind implicit and explicit implementation is rather simple:

  • A member with implicit implementation will be accessible through the interface as well as through the class implementing it
  • A member with explicit implementation will be accessible through the interface only

As for why and when you would use one or another, it depends. In the case you're implementing more than one interface with the same property/method, explicit implementation is your only option, as it is the only way to know which property/method you're intending to call. Obviously in this scenario you can't have that property/method on the class itself: if there is, it will be class only, and will not match any of the interfaces (which will have their explicit implementation of it).

In other scenarios, it really depends on your design choices and what you're trying to accomplish. If you want to force the caller to access interface members only through interface, and not through class declaration, do an explicit implementation.

Say you have two interfaces, IDoStuff<T> and IDoStuff , which your class implements. They both have a method "GetStuff", but one has the signature T GetStuff() , and the other has the signature object GetStuff() .

The problem is that .net will not let you have two methods named the same thing that only differ on the return type. But you need to have both of these methods in your class to satisfy both interfaces. If T is, in fact, an object , then you can use explicit implementation like so.

public T GetStuff()
{
  T stuff;
  //Stuff Is Got
  return stuff;
}

IDoStuff.GetStuff()
{
  return (object)GetStuff();
}

Note that because IDoStuff mandates the security requirements of GetStuff , IDoStuff.GetStuff will be public/private/protected/internal based on that interface's declaration.

If you wanted, you could do every implantation explicitly, but the full method name for each would be InterfaceName.MethodName , and that gets a little annoying to read and write. Usually this is only used when you want to implement a method with the same signature multiple times to satisfy several interfaces.

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