将列表分配给列表的派生类型

时间:2019-08-02 09:26:20

标签: c# collections casting

我需要将通用列表转换为自定义集合。看看:

public class MyCustomType
{ }


public class MyCustomTypeCollection : List<MyCustomType>, IMyCustomTypeCollection
{

}

public interface IMyCustomTypeCollection : IList<MyCustomType>
{

}

public class DemoCast
{

    public void Cast()
    {
        IMyCustomTypeCollection collection = new List<MyCustomType>();
    }
}

演员表看起来如何?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以做

 IMyCustomTypeCollection collection = new MyCustomTypeCollection();

在这种情况下,collection将是MyCustomTypeCollectionList<MyCustomType>的{​​{1}}

您不需要IMyCustomTypeCollection => IList<MyCustomType>,因为您已经拥有List<MyCustomType>IList<MyCustomType>

相关问题