2

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

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

public class C:I
{
    public List<int> f { get; set; }
}

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

4

2 回答 2

6

您可以使用类型的支持字段,List<int>但将其公开为IEnumerable<int>

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

public class C:I
{
    private List<int> f;
    public IEnumerable<int> F
    {
        get { return f; }
        set { f = new List<int>(value); }
    }
}
于 2010-09-15T07:40:04.893 回答
1

您还可以通过显式指定接口来隐藏IEnumerable<int> fI

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时,只有一个f成员可见:IList<int> f. 但是,当您将课程投射到您时,I您可以再次访问该IEnumerable<int> f成员。

C c = new C();
List<int> list = c.f;   // No casting, since C.f returns List<int>.
于 2010-09-15T08:37:18.160 回答