Any reason the interface reference will be included before the method name in the implementation class?

Is there a reason why an interface reference will be included before the method name in the implementation class? For example, let's say you have a ReportService: IReportService and a GetReport (int reportId) method. I was looking at the code, and another developer implemented such a method in ReportService:

Report IReportService.GetReport(int reportId) { //implementation } 

I have never seen an implementation of a service like before. Does it serve any purpose?

+6
source share
1 answer

This is called an "explicit interface implementation". The reason for this may be, for example, a name conflict.

Consider the IEnumerable and IEnumerable<T> interfaces. One declares a non-generic method

 IEnumerator GetEnumerator(); 

and the other is general:

 IEnumerator<T> GetEnumerator(); 

In C #, it is not allowed to have two methods with the same name that differ only in return type. Therefore, if you implement both interfaces, you need to declare one method explicit:

 public class MyEnumerable<T> : IEnumerable, IEnumerable<T> { public IEnumerator<T> GetEnumerator() { ... // return an enumerator } // Note: no access modifiers allowed for explicit declaration IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); // call the generic method } } 

Explicitly implemented interface methods cannot be called on instance variables:

 MyEnumerable<int> test = new MyEnumerable<int>(); var enumerator = test.GetEnumerator(); // will always call the generic method. 

If you want to call a non-generic method, you need to drop test to IEnumerable :

 ((IEnumerable)test).GetEnumerator(); // calls the non-generic method 

This also, apparently, is the reason that access modifiers (for example, public or private ) are not allowed in explicit implementations: in any case, it is not displayed in the type.

+12
source

Source: https://habr.com/ru/post/1013649/


All Articles