当泛型类型约束相同时,为什么我会收到 'Invalid Parameters' 错误?

Why am I getting an 'Invalid Parameters' error when the generic type constraints are the same?

在下面的代码中,我在 'action(u)'、"Invalid Parameters" 处收到错误,即使泛型的类型约束是相同的。为什么会这样,我能做什么?

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

            Action<T> action;

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

        }

UT 是不一样的,即使它们来自相同的基数 class.

假设 SampleA 代表动物,你这样做

public class Bird :  SampleA { }

public class Dog :  SampleA { }

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

字段 action 现在知道如何对 Bird 执行操作,但不知道如何对您传递给它的 Dog 执行操作,即使它们共享一个接口和公共基础 class。

您可以通过更改此行来完成这项工作

Action<T> action;

Action<SampleA> action;