4

Possible Duplicate:
Why isn't there generic variance for classes in C# 4.0?

Example:

interface foo<out T> where T : BaseThing { }

compiles

class foo<out T> where T : BaseThing { }

does not.

Is this just unsupported, or is there some reason why it can never work or doesn't make logical sense?

Edit: Here's what I Wanted to do in case someone was wondering...

        class BaseThing { }
        class DerivedThing : BaseThing { }

        class foo<out T> where T : BaseThing { }
        class bar : foo<DerivedThing> { }

        private void test()
        {
            foo<BaseThing> fooInstance = new bar();
        }
4

1 回答 1

3

修饰符告诉编译器out类型参数可以是协变的。这意味着 T 类型的使用可能更加衍生。由于您使用的是特定类(例如构造的泛型类型),因此只有一个具体类型的实例,因此没有更多派生类型在起作用。多种类型可以实现像 foo 这样的接口,这意味着您正在处理可能不同类型的 T,在这种情况下,这些 T 类型中的一个可能派生更多。

于 2012-08-10T19:05:12.340 回答