C# 错误:列表<;int>;不具有';System.Collections.Generic.IEnumerable<;int>;

C# 错误:列表<;int>;不具有';System.Collections.Generic.IEnumerable<;int>;,c#,interface-implementation,C#,Interface Implementation,如何使用列表实现接口成员“f” public interface I { IEnumerable<int> f { get; set; } } public class C:I { public List<int> f { get; set; } } 公共接口I { IEnumerable f{get;set;} } 公共C类:I类 { 公共列表f{get;set;} } 错误1“ClassLibrary1.C”未实现接口成员“ClassLibrar

如何使用列表实现接口成员“f”

public interface I
{
    IEnumerable<int> f { get; set; }
}

public class C:I
{
    public List<int> f { get; set; }
}
公共接口I
{
IEnumerable f{get;set;}
}
公共C类:I类
{
公共列表f{get;set;}
}

错误1“ClassLibrary1.C”未实现接口成员“ClassLibrary1.I.f”ClassLibrary1.C.f“”无法实现“ClassLibrary1.I.f”,因为它没有匹配的返回类型“System.Collections.Generic.IEnumerable”。c:\users\admin\documents\visualstudio 2010\Projects\ClassLibrary1\Class1.cs

您可以使用类型为
List
的备份字段,但将其公开为
IEnumerable

公共接口I
{
IEnumerable F{get;set;}
}
公共C类:I类
{
私人名单f;
公共IEnumerable F
{
获取{return f;}
集合{f=新列表(值);}
}
}

您还可以通过显式指定接口来隐藏
I
IEnumerable f

public class C : I
{
    private List<int> list;

    // Implement the interface explicitly.
    IEnumerable<int> I.f
    {
        get { return list; }
        set { list = new List<int>(value); }
    }

    // This hides the IEnumerable member when using C directly.
    public List<int> f
    {
        get { return list; }
        set { list = value; }
    }
}
public class C : I
{
    private List<int> list;

    // Implement the interface explicitly.
    IEnumerable<int> I.f
    {
        get { return list; }
        set { list = new List<int>(value); }
    }

    // This hides the IEnumerable member when using C directly.
    public List<int> f
    {
        get { return list; }
        set { list = value; }
    }
}
C c = new C();
List<int> list = c.f;   // No casting, since C.f returns List<int>.