Do things with objects as if they were parents

The following code gives me an error saying in my call doStuffToLines(segments)

there are invalid arguments.

Can't I do this since I have a Lines DimensionLineSegment inheritance?

  private void doStuff() { List<DimensionLineSegment> segments = new List<DimensionLineSegment>(); doStuffToLines(segments); } private void doStuffToLines(List<Line> lines) { } 
+6
source share
1 answer

You cannot pass a specific type to a method because List is not covariant.

You can try something like this:

 public void doStuffToLines<T>(IList<T> lines) where T : Line { //do some thing } 

By specifying a general constraint, you can restrict the generic type passed to an object of type Line or its descendants.

It should be noted that if you are using .NET 4.0, you can change your method to List to IEnumerable, because the general parameter T is covariant.

+3
source

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


All Articles