【问题标题】:C#: ICollection with Interface as Type like ICollection<ILocalized>C#:具有接口的 ICollection 类型为 ICollection<ILocalized>
【发布时间】:2013-11-22 09:16:07
【问题描述】:

我正在使用生成我的实体类的 EntitFramework:

我有这些课程:

public class Car
{
    //...
    public String Brand { get; set; }
    //...

    public virtual ICollection<CarLocalized> CarLocalizeds { get; set; }
    //...
}

public class CarLocalized :ILocalized
{
    public int LangID { get; set; }

    public Lang Lang { get; set; }
}

public static class Helper {
    public static List<String> GetLangIDList(ICollection<ILocalized> list)
    {
        //I want all the ID of the lang where car is translated for:
        var somethin = list.Select(m => m.LCID_SpracheID.ToString()).ToList();
        return somethin;
    }
}

public class HomeController : Controller
{
    public ActionResult Translated()
    { 
        Car car = db.Cars.Find(2);
        List<String> transletedIDs = Helper.GetLangIDList(car.CarLocalizeds);

        return View(transletedIDs);
    }

}

但现在的问题是

List<String> transletedIDs = Helper.GetLangIDList(car.CarLocalizeds);

不工作。为什么我不能将签名设置为 ICollection 并给它一个 ICollection,其中 CarLocalized 实现了签名中所需的接口??

请帮帮我...

THx

【问题讨论】:

    标签: c# signature icollection


    【解决方案1】:

    问题是ICollection&lt;T&gt; 不是“协变”。 GetLangIDList 方法似乎没有修改列表,它只是查询列表。在这种情况下,您可以使用“协变”IEnumerable&lt;T&gt;

    public static List<String> GetLangIDList(IEnumerable<ILocalized> list)
    {
        //I want all the ID of the lang where car is translated for:
        var somethin = list.Select(m => m.LCID_SpracheID.ToString()).ToList();
        return somethin;
    }
    

    阅读更多关于Covariance and Contravariance in GenericsFaq的信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      相关资源
      最近更新 更多