【问题标题】:Using an Interface for Collection<> generic type [duplicate]使用 Collection<> 泛型类型的接口 [重复]
【发布时间】:2014-09-19 08:28:40
【问题描述】:

我在 c# 中有这些类型

public class A : IA
{

}

public interface IA
{

}

public class B
{
    public B()
    {
        A = new List<A>(); //Where I have problem
    }

    public ICollection<IA> A { get; set; }
}

我遇到了这个转换错误:

无法将类型“System.Collections.Generic.List”隐式转换为 'System.Collections.Generic.ICollection'。显式转换 存在(您是否缺少演员表?)

我怎么能做这种事!

【问题讨论】:

标签: c# generics collections interface casting


【解决方案1】:

您不能将 List 隐式转换为 List。如果你想这样做,你需要决定集合是应该包含 A 还是 IA。 这是一个修复:

public class B
{
    public B()
    {
        A = new List<IA>();
    }

    public ICollection<IA> A { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    相关资源
    最近更新 更多