如何将接口方法的返回类型定义为另一个接口? [英] How do I define the return type of an interface method to be another interface?

查看:192
本文介绍了如何将接口方法的返回类型定义为另一个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是接口和抽象类的新手。我想创建几个接口来定义购物车系统对象的核心方法和变量。然后我想创建实现核心功能的抽象类。这个想法是,其他类可以以不同的方式用于不同的项目。

I'm new to interfaces and abstract classes. I want to create a couple of interfaces to define core methods and variables for the objects for a shopping cart system. Then I want to create abstract classes which implement the core functions. The idea is that they can be used by other classes in slightly different ways for different projects.

这是我的(简化的)接口:

Here are my (cut-down) interfaces:

public interface ICart
{
    ...
    List<ICartItem> CartItems { get; set; }
}

public interface ICartItem
{
    int ProductId { get; set; }
    int Quantity { get; set; }
}

这是我的抽象Cart类(再次,仅显示相关行)实现ICart:

And here is my abstract Cart class (again, only showing relevant lines) which implements ICart:

public abstract class Cart : ICart
{

    private List<CartItem> _cartItems = new List<CartItem>();

    public List<CartItem> CartItems 
    {
        get
        {
            return _cartItems;
        }
    }
}

我的CartItem类实现了ICartItem:

And my CartItem class which implements ICartItem:

public abstract class CartItem : ICartItem
{
    ...
}

当我尝试编译类时,我收到一条错误消息:'Cart'没有实现接口成员' CartItems'。 'Cart.CartItems'无法实现'ICart.CartItems',因为它没有匹配的返回类型System.Collections.Generic.List< ICartItem>。

When I try to compile the classes I get an error saying: 'Cart' does not implement interface member 'CartItems'. 'Cart.CartItems' cannot implement 'ICart.CartItems' because it does not have the matching return type of System.Collections.Generic.List<ICartItem>.

我以为这里的想法是接口可以由许多类实现,这些类以不同的方式执行核心功能并添加新的方法等。为什么我的接口需要知道实际使用的是什么类,只要那个class实际上是否正确实现了接口?

I thought that the idea here is that the interface can be implemented by a number of classes which perform the core functions in different ways and add new methods, etc. Why would my interface need to know what class is actually being used, just as long as that class actually implements the interface correctly?

推荐答案

您需要在C#2中使用泛型来实现:

You need to user generics in C# 2 to achieve that:

public interface ICart<T> where T : ICartItem
{
    // ...
    List<T> CartItems { get; set; }
}

public abstract class Cart : ICart<CartItem>
{
    // ...
    public List<CartItem> CartItems { get; set; }
}

这篇关于如何将接口方法的返回类型定义为另一个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆