您可以使用显式接口实现有效地重载返回类型:
Driver IDriverService.New()
{
return New(); // Calls the method below
}
public SubclassOfDriver New()
{
return new SubclassOfDriver();
}
现在,任何只知道您的实现作为接口实现的代码都将看到显式接口实现方法,并且只期望返回类型为Driver
.
任何通过具体类型引用服务的代码只会看到第二种方法,并期望返回类型为SubclassOfDriver
. 例如:
SpecialFactory specialFactory = new SpecialFactory();
SubclassOfDriver subclassDriver = specialFactory.New(); // Fine
IDriverFactory generalFactory = specialFactory;
IDriver generalDriver = generalFactory.New(); // Fine
// This wouldn't compile
SubclassOfDriver invalid = generalFactory.New();
或者,您可能希望使您的界面通用:
public interface IDriverFactory<TDriver> where TDriver : Driver
{
TDriver New();
}
public class SpecialDriverFactory : IDriverFactory<SubclassOfDriver>
{
public SubclassOfDriver New()
{
return new SubclassOfDriver();
}
}