C# 无法将项转换为其接口异常

C# 无法将项转换为其接口异常,c#,exception,interface,C#,Exception,Interface,我有以下类和接口: public interface IFieldFiller { string Content { get; set; } Boolean Nullable { get; set; } string Name { get; set; } } 及 然后,我使用以下Linq语句构建这些对象的列表: Fields = temp.merged_fields.Select(f => new FieldFiller

我有以下类和接口:

public interface IFieldFiller
    {
        string Content { get; set; }
        Boolean Nullable { get; set; }
        string Name { get; set; }
    }

然后,我使用以下Linq语句构建这些对象的列表:

Fields =  temp.merged_fields.Select(f => new FieldFiller { Name = f.name, NameSpace = f.@namespace, StoredProcedure = new StoredProcedure { Name = f.sproc1.name, Parameters = f.field_params.ToDictionary(p => p.sprocParam.name, p=>p.value)}}).ToList()
我一直得到以下例外:

Error   1   Cannot implicitly convert type 'System.Collections.Generic.List<Services.Data.EmailTemplateAccess.Contracts.FieldFiller>' to 'System.Collections.Generic.List<Services.Data.EmailTemplateAccess.Contracts.IFieldFiller>'    
错误1无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”

我不明白为什么FieldFiller实现IFieldFiller时会出现此错误。我已经验证了它们是否在正确的名称空间中。任何帮助都将不胜感激。

FieldFiller
也是
IFieldFiller
,但是
List
不是
List
,您可以相应地强制转换它:

Fields =  temp.merged_fields
    .Select(f => (IFieldFiller)new FieldFiller { Name = f.name, NameSpace = f.@namespace, StoredProcedure = new StoredProcedure { Name = f.sproc1.name, Parameters = f.field_params.ToDictionary(p => p.sprocParam.name, p=>p.value)}})
    .ToList()
或者,对于.NET 4,您可以使用以下内容(请参阅:):

。。。
.Select(f=>newfieldfiller{…})
.ToList();
为什么不安全:


  • D:B
    并不意味着
    List:List
    。您需要手动将
    D
    元素添加到
    List
    中。根据该博客,FieldFiller是否会比IFieldFiller小,从而使其成为一个协变关系,编译器应该能够合理化?抱歉,我在重新阅读您的问题后编辑了我的注释。仅在接口上允许协方差。这是一个非常常见的问题:假设某些类型的集合与其内容具有相同的关系。协变/反变是解决这些问题的方法,但对于您的需求来说是不必要的,但如果您感兴趣,仍然值得一读。
    Fields =  temp.merged_fields
        .Select(f => (IFieldFiller)new FieldFiller { Name = f.name, NameSpace = f.@namespace, StoredProcedure = new StoredProcedure { Name = f.sproc1.name, Parameters = f.field_params.ToDictionary(p => p.sprocParam.name, p=>p.value)}})
        .ToList()
    
    ...
        .Select(f => new FieldFiller { ... })
        .ToList<IFieldFiller>();