为什么不能在接口定义中使用IList然后使用List实现此属性?我在这里遗漏了什么,或者只是C#编译器不允许这样做?
public interface ICategory
{
IList<Product> Products { get; }
}
public class Category : ICategory
{
public List<Product> Products { get { new List<Product>(); } }
}
Run Code Online (Sandbox Code Playgroud)
编译器说错误82'类别'没有实现接口成员'ICategory.Products'.'Category.Products'无法实现'ICategory.Products',因为它没有匹配的返回类型'System.Collections.Generic.IList'
将您的代码更改为:
public interface ICategory
{
IList<Product> Products { get; }
}
public class Category : ICategory
{
// Return IList<Product>, not List<Product>
public IList<Product> Products { get { new List<Product>(); } }
}
Run Code Online (Sandbox Code Playgroud)
实现它时,无法更改接口方法的签名.
接口的方法和实现接口方法的具体方法必须完全匹配。一种选择是显式接口实现,它允许您满足接口,同时在类型上保留更具体的公共 API。通常只是代理方法,因此不存在代码重复:
public interface ICategory
{
IList<Product> Products { get; }
}
public class Category : ICategory
{
IList<Product> ICategory.Products { get { return Products ; } }
public List<Product> Products { get { ...actual implementation... } }
}
Run Code Online (Sandbox Code Playgroud)