【问题标题】:Why can't the OUT generic modifier by applied to classes as well as interfaces? [duplicate]为什么不能将 OUT 泛型修饰符应用于类和接口? [复制]
【发布时间】:2012-08-10 18:59:45
【问题描述】:

可能重复:
Why isn't there generic variance for classes in C# 4.0?

例子:

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

编译

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

没有。

这只是不受支持,还是出于某种原因它永远无法工作或没有逻辑意义?

编辑:如果有人想知道,这就是我想做的事情......

        class BaseThing { }
        class DerivedThing : BaseThing { }

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

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

【问题讨论】:

  • 好吧,documentation 表示 out 仅支持接口和委托。至于为什么要这样设计,我相信 Eric Lippert 最终会看到这个问题并给你一个全面的答案(没有足够的用例,或者所有用例都不常见等等......)。

标签: c#


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-09-20
    • 2018-02-10
    • 2011-08-27
    • 2023-03-12
    • 2023-02-21
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多