Error: List<int> does not have the matching of 'System.Collections.Generic.IEnumerable<int>
H开发者_如何转开发ow to implement interface members "f" with the list?
public interface I
{
IEnumerable<int> f { get; set; }
}
public class C:I
{
public List<int> f { get; set; }
}
Error 1 'ClassLibrary1.C' does not implement interface member 'ClassLibrary1.I.f'. 'ClassLibrary1.C.f' cannot implement 'ClassLibrary1.I.f' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'. c:\users\admin\documents\visual studio 2010\Projects\ClassLibrary1\Class1.cs
You can use a backing field of type List<int>
but expose it as 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); }
}
}
You can also hide IEnumerable<int> f
of I
by specifying the interface explicitly.
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; }
}
}
When using you class C
, there is only one f
member visible: IList<int> f
. But when you cast your class to I
you can access the IEnumerable<int> f
member again.
C c = new C();
List<int> list = c.f; // No casting, since C.f returns List<int>.
精彩评论