2010-09-15 100 views
2

如何使用列表實現接口成員「f」?錯誤:列表<int>沒有匹配'System.Collections.Generic.IEnumerable <int>

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

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

錯誤1'ClassLibrary1.C'沒有實現接口成員'ClassLibrary1.I.f'。 'ClassLibrary1.C.f'不能實現'ClassLibrary1.I.f',因爲它沒有匹配的返回類型'System.Collections.Generic.IEnumerable'。 C:\用戶\ ADMIN \文檔\ Visual Studio 2010的\項目\ ClassLibrary1的\的Class1.cs

回答

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); } 
    } 
} 
1

您還可以隱藏通過明確指定接口,可以獲得IIEnumerable<int> 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; } 
    } 
} 

使用您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>. 
相關問題