0

我希望有一个接口指定该接口的任何实现必须在其方法声明中使用特定接口的子类型:

interface IModel {} // The original type

interface IMapper {
    void Create(IModel model); // The interface method
}

所以现在我希望我的这个接口的实现不是期望IModel它本身,而是一个IModel类型:

public class Customer : IModel {} // My subtype

public class CustomerMapper : IMapper {
    public void Create(Customer customer) {} // Implementation using the subtype
}

目前我收到以下错误:

“CustomerMapper”未实现接口成员“IMapper.Create(IModel)”

有没有办法可以做到这一点?

4

1 回答 1

5

您需要使您的接口在它应该期望的值类型中具有通用性:

interface IMapper<T> where T : IModel
{
    void Create(T model);
}

...

public class CustomerMapper : IMapper<Customer>
{
    public void Create(Customer model) {}
}

如果你不让它通用,任何只知道接口的东西都不知道什么样的模型是有效的。

于 2012-10-22T10:40:11.727 回答