通用集合碰撞 [英] Generic collection collision

查看:140
本文介绍了通用集合碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public interface IFoo 
{


$ b $ public class Foo:IFoo {}

public class Bar:IFoo {}

public class CollectionOf< T> :列出< IFoo>
{

}

public class Bars:CollectionOf< Bar>
{

}

public class Test
{
public void Test()
{
CollectionOf<的IFoo> bars = new Bars();




$ b

编译器抱怨实例化。酒吧是IFoos的集合。是否这是协变/逆变问题之一?

解决方案

解决方案,如果有的话将取决于它不是什么为你工作。我可以通过两种方式让您的示例进行编译,可以使用IEnumerable或将CollectionOf定义为具有out泛型修饰符的接口。无论是哪一种解决方案我都不知道:

  public interface IFoo {} 

public class Foo:IFoo {}

public class Bar:IFoo {}

public interface CollectionOf< out T> :IEnumerable< IFoo> {}

public class Bars:CollectionOf< Bar> {}

public class Test
{
public void Test()
{
IEnumerable< IFoo> bars1 =新Bars();
CollectionOf< IFoo> bars2 =新Bars();
}
}


Here's my best attempt to recreate the situation.

public interface IFoo
{

}

public class Foo : IFoo { }

public class Bar : IFoo { }

public class CollectionOf<T> : List<IFoo>
{

}

public class Bars : CollectionOf<Bar>
{

}

public class Test
{
    public void Test()
    {
        CollectionOf<IFoo> bars = new Bars();
    }
}

Compiler complains on the instantiation. Bars is a collection of IFoos. Is this one of those covariance/contravariance issues?

解决方案

The fix, if there is one would depend on what it is that's not working for you. I can get your example to compile in two ways, either use IEnumerable or define your CollectionOf as an interface with the out generic modifier. Whether either is a fix for you I don't know:

public interface IFoo { }

public class Foo : IFoo { }

public class Bar : IFoo { }

public interface CollectionOf<out T> : IEnumerable<IFoo> { }

public class Bars : CollectionOf<Bar> { }

public class Test
{
    public void Test()
    {
        IEnumerable<IFoo> bars1 = new Bars();
        CollectionOf<IFoo> bars2 = new Bars();
    }
}

这篇关于通用集合碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆