Why do I get an "Invalid parameters" error when the general type restrictions are the same?

In the code below, I get the error message "action (u)", "Invalid Parameters", even if the type restrictions for generics are the same. Why is this and what can I do?

        public class Test<T> : IDoStuff where T : SampleA
        {

            Action<T> action;

            void DoStuff<U>(U u) where U : SampleA
            {
                action(u);
            }

        }
+4
source share
2 answers

Say SampleA represents animals, and you do it

public class Bird :  SampleA { }

public class Dog :  SampleA { }

Test<Bird> b = new Test<Bird>();
b.DoStuff<Dog>();

The field actionnow knows how to act on the Bird, but not on the Dog that you passed, even if they have a common interface and a common base class.

You can do this work by changing this line

Action<T> action;

to

Action<SampleA> action;
+4
source

Uand Tdo not match, even if they are derived from the same base class.

+2
source

All Articles