C# 在接口中:指定实现的方法必须采用接口的子类型?
我想让接口指定该接口的任何实现必须在其方法声明中使用特定接口的子类型:C# 在接口中:指定实现的方法必须采用接口的子类型?,c#,inheritance,interface,C#,Inheritance,Interface,我想让接口指定该接口的任何实现必须在其方法声明中使用特定接口的子类型: interface IModel {} // The original type interface IMapper { void Create(IModel model); // The interface method } 因此,现在我希望这个接口的实现不是期望IModel本身,而是期望IModel的子类型: public class Customer : IModel {} // My subtype p
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)”
有什么方法可以做到这一点吗?您需要使您的界面具有它应该期望的值类型:
interface IMapper<T> where T : IModel
{
void Create(T model);
}
...
public class CustomerMapper : IMapper<Customer>
{
public void Create(Customer model) {}
}
接口IMapper,其中T:IModel
{
空洞生成(T型);
}
...
公共类CustomerMapper:IMapper
{
公共void创建(客户模型){}
}
如果您不将其设置为泛型,那么任何只知道接口的东西都无法知道哪种模型是有效的。您需要将接口设置为它所期望的值类型的泛型:
interface IMapper<T> where T : IModel
{
void Create(T model);
}
...
public class CustomerMapper : IMapper<Customer>
{
public void Create(Customer model) {}
}
接口IMapper,其中T:IModel
{
空洞生成(T型);
}
...
公共类CustomerMapper:IMapper
{
公共void创建(客户模型){}
}
如果您不将其通用化,任何只知道接口的东西都无法知道哪种模型是有效的。Ah!正是我想要的。我不知道如何搜索那个语法。我必须在两个地方都用同样的说法吗?或者我可以在接口中称之为“模型”,在实现中称之为“客户”吗?我刚刚尝试过,它似乎使用了不同的参数name@RobinWinslow:您可以更改参数名称,但是请注意,如果调用方使用命名参数,这将破坏Liskov替换原则。在任何情况下,这会破坏实际代码吗?啊!正是我想要的。我不知道如何搜索那个语法。我必须在两个地方都用同样的说法吗?或者我可以在接口中称之为“模型”,在实现中称之为“客户”吗?我刚刚尝试过,它似乎使用了不同的参数name@RobinWinslow:您可以更改参数名称,但是请注意,如果调用方使用命名参数,这将破坏Liskov替换原则。在任何情况下,这会破坏实际代码吗?