我已经阅读了所有关于协方差,逆变和不变性的内容,但我仍然没有得到如何设计我的代码

时间:2016-11-23 08:06:12

标签: c# generics covariance nested-generics invariance

在发布此内容之前,我一直在搜索和阅读/研究。我发现了类似的问题,但大多数帖子实际上更多地涉及将“派生类型列表”传递给需要“基类型列表”的函数调用。我可以欣赏动物的例子,感觉我在学习后有更好的掌握。

话虽如此,我仍然无法弄清楚如何在我的特定用例中解决。我需要在集合中聚合“GenericClass of TestInterface(s)”的实例。我已经尽力复制/粘贴了最好的方法来完成任务。

<Reference Include="SExtension" Condition="'$(Configuration)' == 'ver3'">
    <HintPath>..\..\_libBinary\ver3\SExtension.dll</HintPath>
</Reference>

上述代码因以下编译错误而失败:

  

错误CS1503:参数1:无法从'Covariance.GenericClass'转换为'Covariance.GenericClass'

     

错误CS1503:参数1:无法从'Covariance.GenericClass'转换为'Covariance.GenericClass'

非常感谢任何帮助/指导或相关链接。如果这是一个重复的问题,我再次道歉。谢谢!

1 个答案:

答案 0 :(得分:4)

您只能在通用接口而不是类型上声明方差修饰符(in,out)。因此,解决此问题的一种方法是为GenericClass声明接口,如下所示:

interface IGenericClass<out TemplateClass> where TemplateClass : TestInterface {
    TemplateClass goo { get; }
}
class GenericClass<TemplateClass> : IGenericClass<TemplateClass> where TemplateClass : TestInterface
{
    public TemplateClass goo { get; }
}

然后

class Program {
    protected static ISet<IGenericClass<TestInterface>> set = new HashSet<IGenericClass<TestInterface>>();

    static void Main(string[] args) {
        set.Add(new GenericClass<A>());
        set.Add(new GenericClass<B>());
    }
}