Why does class C# not support convulsion and countervailability?



  • Why only the interfaces and delegates at C# support the quarry and countervariability technique in Generic types?



  • Good question.

    A simple, superficial answer is because it has not yet been implemented in the language. But why wasn't it implemented? Look.

    The problem is that C# emerged as a purely peremptory language in which the main type of data structures is mutate (i.e., variablesData structures. Now imagine you have a class. C<out T>♪ What are you gonna do with the type? T?

    You can't have a method with a type input parameter. T♪ Because because out You might actually have a type that's a base for the entry. T (in terms of contrast, so the key word is used out: T may only meet in &quot; relevant &quot; positions as reverted &quot; .

    The same applies to public properties of a type T Sester (and fields), i.e., this is essentially the same function as inlet T

    You won't be able to have a useful privileged mutable field like T♪ Why? Think about how you'll give him some new meaning. Where will you get it? You don't have the methods that take the entrance. Tfor the reasons described, you can only design a copy on your own. So your field is like, T It'll probably be useless.

    No mutable fields of type T, is there a lot of benefits from that parameter? That is why the language developers have decided not to immortalize their support for class countervariability. It's basically the same story, but instead of the impossibility of recording in a field like T You'll face the impossible. reading It's symmetrical.


    The C# language is now developing towards greater support for the functional programming style in which the immutable (unchangeable) data structures are popular. If your data structure is immutable, you can make it consistent. It's best to see. https://blogs.msdn.microsoft.com/ericlippert/2007/12/06/immutability-in-c-part-three-a-covariant-immutable-stack/ (sighs)+T read out T) It is therefore hoped that support for class options will be added in the following language versions.


    Ideas of reply retained https://stackoverflow.com/a/2734070/276994 , co-contractor and C#.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2