4
There are some entities in the application that I am developing that need to be sorted by a predefined routine.
Thinking about it was created contract class, called ElementoOrdenavel
and all entities that can be ordered inherit from this class.
She exposes, a priori, only two members. Here is the class code.
public abstract class ElementoOrdenavel
{
public int Id { get; set; }
public int Ordem { get; set; }
}
Example of a class that inherits from this
public class Banner : ElementoOrdenavel
{
public string Descricao { get; set; }
}
To facilitate my work, I made a method that receives a list of ElementoOrdenavel
and does the work of ordination, thus
void Reorganizar(IEnumerable<ElementoOrdenavel> colecao, int[] idsOrdenados)
{
for (int ordem = 0; ordem < idsOrdenados.Length; ordem++)
{
var elemento = colecao.First(m => m.Id == idsOrdenados[ordem]);
elemento.Ordem = ordem + 1;
}
}
And I tried to call this method
var banners = db.Banners.AsEnumerable();
Reorganizar(banners, ids);
And to my surprise, I got the mistake
cannot Convert from '
IEnumerable<Banner>
' to 'IEnumerable<ElementoOrdenavel>
'
A list of Banner
nay is a list of ElementoOrdenavel
?
Making a generic method works normally. Why?
void Reorganizar<T>(IEnumerable<T> colecao, int[] idsOrdenados) where T : ElementoOrdenavel
{
for (int ordem = 0; ordem < idsOrdenados.Length; ordem++)
{
var elemento = colecao.First(m => m.Id == idsOrdenados[ordem]);
elemento.Ordem = ordem + 1;
}
}
How I hate this inheritance ;) I did not read it right, but I think it is a matter of variance: https://answall.com/q/32880/101 and https://answall.com/q/75097/101 and https://answall.com/a/56056/101 and https://en.stackoverflow.com/q/206278/101. Genericity gives you the guarantee that you will be okay.
– Maniero
The first only accepts
IEnumerable<ElementoOrdenavel>
, or has a dynamic polymorphism in theIEnumerable
, but there is no polymorphism in its parameter. There, in C#, the only way to make the parameter of this polymorphic interface precise of generity.– Maniero
I need to get a better look at the case before I answer, I’ll try as soon as I can
– Maniero
I don’t like the inheritance much either, but there would be no other way to fix the contract to make a unique method without using it.
– Jéf Bueno