Rob*_*low 0 c# inheritance interface
我希望有一个接口指定该接口的任何实现必须在其方法声明中使用特定接口的子类型:
interface IModel {} // The original type
interface IMapper {
void Create(IModel model); // The interface method
}
Run Code Online (Sandbox Code Playgroud)
所以,现在我想我实现这个接口来没有想到IModel本身,而是一个亚型的IModel:
public class Customer : IModel {} // My subtype
public class CustomerMapper : IMapper {
public void Create(Customer customer) {} // Implementation using the subtype
}
Run Code Online (Sandbox Code Playgroud)
目前我收到以下错误:
'CustomerMapper'没有实现接口成员'IMapper.Create(IModel)'
有没有办法实现这个目标?
您需要使用它应该期望的值类型使您的接口通用:
interface IMapper<T> where T : IModel
{
void Create(T model);
}
...
public class CustomerMapper : IMapper<Customer>
{
public void Create(Customer model) {}
}
Run Code Online (Sandbox Code Playgroud)
如果你不把它变成通用的,任何只知道接口的东西都不知道哪种模型是有效的.