.Net interface inheritance compilation

Why is this:

public interface IServiceRecherche<T, U> where T : IEntite where U : ICritereRecherche { IList<T> Rechercher(U critere); } public interface IServiceRechercheUnite : IServiceRecherche<IUnite, ICritereRechercheUnite>, {} 

differs from:

 public interface IServiceRechercheUnite { IList<IUnite> Rechercher(ICritereRechercheUnite critere); } 

when compiling?

Applications that were compiled with the first interface could not recognize the second. I know that they are not the same in the code, but at the end at runtime, why don't they match?

+4
source share
2 answers

From the CLR point of view, these are different types, because the first of them is a closed generic type, inherited from IServiceRecherche<T, U> .

but in the end during execution why they are not the same

The reason is the same as in the case of:

 public MyClass1 { public int MyProperty { get; set; } } public MyClass2 { public int MyProperty { get; set; } } 

These are just different type declarations, even though they have similar member declarations.

The CLR cannot think like this: "Ah, MyClass1 and MyClass2 are identical, let them consider them the same."

+2
source

However, you could use duck-typing to "cast" one instance into another. To do this, you need a class representing your duck:

 public class LooksLikeAnIServiceRecherche : IServiceRecherche<IUnite, ICritereRechercheUnite> { private readonly dynamic _duck; public LooksLikeAnIServiceRecherche (dynamic duck) { this._duck = duck; } public IList<IUnite> Rechercher(ICritereRechercheUnite critere) { return this._duck.Rechercher(critere); } } 

The call to the Rechercher method is checked at runtime, not at compile time, thereby preventing you from getting a compiler error.

Using this code is very simple:

 IServiceRechercheUnite rechercheUnite; var serviceRecherche = new LooksLikeAnIServiceRecherche(rechercheUnite); 

For more information on how to use dynamic -keyword, see MSDN: dynamic

0
source

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


All Articles