开发者

Why it is not possible to use IList<T> in interface definition and List<T> in inplementation?

开发者 https://www.devze.com 2023-01-30 16:46 出处:网络
Why it is not possible to use IList in interface definition and then implement this property using List? Am I missing something here or just C# compiler doesn\'t allow this?

Why it is not possible to use IList in interface definition and then implement this property using List? Am I missing something here or just C# compiler doesn't allow this?

public interface ICategory
{
    IList<Product> Products { get; }
}

public class Category : ICategory
{
    public List<Product> Products { get { new List<Product>(); } }        
}

compiler says Error 82 'Category' does not implement开发者_开发知识库 interface member 'ICategory.Products'. 'Category.Products' cannot implement 'ICategory.Products' because it does not have the matching return type of 'System.Collections.Generic.IList'


Change your code to:

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

You cannot change the signature of an interface method when you implement it.


It has to be an exact match between the interface's method and the concrete method that implements the interface's method. One option is explicit interface implementation, which allows you to satisfy the interface while keeping your more-specific public API on the type. And usually just proxy the methods, so there is no code duplication:

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... } }        
}


This would work

public interface ICategory<out T> where T:IList<Product>
    {
        T Product { get; }
    }

public class Category : ICategory<List<Product>>
    {
        public List<Product> Products
        {
            get
            {
                throw new NotImplementedException();
            }
        }
    } 

Although complicated but possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号