0

我有一个像下面这样的结构。我在返回通用集合时遇到了一些麻烦。我错过了什么?

class Program
{
    static void Main()
    {
          BusinessCollection businessCollection = new BusinessCollection();

          //Why this is not working because businesscollection is a GenericCollection<BusinessEntity>
          businessCollection = new GenericCollection<BusinessEntity>();

          //or neither this
         businessCollection = (BusinessCollection)new GenericCollection<BusinessEntity>();
    }
}



public class BusinessEntity
{
   public string Foo { get; set;}
}

public class BusinessCollection : GenericCollection<BusinessEntity>
{
     //some implementation here
}

public class GenericCollection<T> : ICollection<T>
{
    //some implementation here
}
4

4 回答 4

5

你不能做你想做的事。反过来也行。

所有BusinessCollection确实是,GenericCollection<BusinessEntity>但你不能肯定地说所有GenericCollection<BusinessEntity>都是BusinessCollection

因此,以下将起作用。

class Program
{
    static void Main()
    {
          GenericCollection<BusinessEntity> businessCollection = new BusinessCollection();
          //this will work
          BusinessCollection tempCollection = (BusinessCollection)businessCollection ;
    }
}



public class BusinessEntity
{
   public string Foo { get; set;}
}

public class BusinessCollection : GenericCollection<BusinessEntity>
{
     //some implementation here
}

public class GenericCollection<T> : ICollection<T>
{
    //some implementation here
}
于 2012-07-19T12:53:16.867 回答
2

检查你的假设:

businesscollection is a GenericCollection<BusinessEntity>

是的,但是您将其声明为 type Businesscollection。并非全部GenericCollection<BusinessEntity>都是,BusinessCollection但这就是您要分配给BusinessCollection.

于 2012-07-19T12:53:13.013 回答
2

因为正方形是长方形,但并非所有长方形都是正方形。在这种情况下, aBusinessCollection是 a GenericCollection<BusinessEntity>,但并非所有GenericCollection<BusinessEntity>对象都是BusinessCollection对象。类型为 a 的变量BusinessCollection可以指向一个GenericCollection<BusinessEntity>对象,但反之则不行。

于 2012-07-19T12:54:06.087 回答
2

businessCollections键入为BusinessCollection; 它只能分配一个. _ BusinessCollection然而,GenericCollection<BusinessEntity>() 不是一个BusinessCollection。就像“动物”不是“狗”(但“狗”是“动物”)。

这可以在运行时或编译时进行验证。运行时选项是您的演员:

businessCollection = (BusinessCollection){some expression};

这是使用“动物”可能是“狗”测试,即检查我们正在考虑的特定动物是否实际上狗。它将此检查推迟到运行时。这就是为什么这条线可以编译,但实际上并没有运行。特定的动物从来都不是真正的狗。

于 2012-07-19T12:54:12.790 回答