Good day to all. Maybe someone has already come across this and can help?

public static class JSON { public static string Serialize_object_TO_JSON<T>(this T Entity) where T:ENT { return JsonConvert.SerializeObject(Entity); } } 

There is a certain class which inherits ENT and it is possible to transfer it to attributes. Then I had to redo the method so that it worked with the collections:

 public static class JSON { public static string Serialize_object_TO_JSON<T>(this T Entity) where T:List<ENT> { return JsonConvert.SerializeObject(Entity); } } 

After that, the compiler says that it failed to cast the class type that inherits from ENT to the type List<ENT> .

PS Initially, I cannot set a generalization of a finite class, since There are quite a lot of them, that's why I tried to do it through inheritance.

  • one
    show how you call - Igor
  • one
    If in any part of the program you can transfer any collection to the JsonConvert.SerializeObject method and get a JSON object, then why JsonConvert.SerializeObject you need to JsonConvert.SerializeObject your own serialization method for a separate object collection? This is not a duplication? - Adam
  • 2
    Try this: public static string Serialize_object_TO_JSON<T>(this List<T> Entity) where T:ENT - Grundy
  • @adamshakhabov There are a lot of objects in the project that need to be serialized, there is no particular problem in this, but in order to get objects from them you need to exactly mean the type of object. - LurKha

1 answer 1

Try this if business logic allows you to:

 public static class JSON { public static string Serialize_object_TO_JSON<T>(this T Entity) where T : IEnumerable<ENT> { return JsonConvert.SerializeObject(Entity); } } 

The fact is that List<T> is invariant. And all classes in .NET are invariant. That is, this is a complete type matching.

Means that you can use only the initially specified type. Thus, the parameter of an invariant universal type is neither covariant nor contravariant.

On the other hand, there is an IEnumerable<out T> where the type-parameter T marked as out is covariant.

Allows you to use a type with a greater depth of inheritance than originally set.

Full description why so

+1 for a good example

  • Here, it seems to me, this is not the case, but that List<Descendant> not a successor of List<Base> . - Igor
  • @Igor, well, as if any two List<T> and List<U> do not have a base-derived relationship, or what are you talking about, I can’t understand your idea correctly? - Anton Komyshan
  • Yes, perfect. Applied in the project - everything works like a clock. Thank you very much for the decision and for the materials on this topic - I will go to understand :) - LurKha
  • one
    @AntonKomyshan - thanks, didn’t know about IEnumerable<out T> - Igor