Arm*_*ada 1 c# inheritance casting interface
我在C#中使用ASP.NET MVC.我正在创建服务类.我有一个驱动程序服务接口的服务接口(IDriverService).
它具有以下方法定义:
Driver New();
Run Code Online (Sandbox Code Playgroud)
我有两个这个接口的实现,它实现了这个方法:
Driver New()
{
return new Driver();
}
Driver New()
{
return new SubclassOfDriver();
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,一个实现通过返回基本驱动程序来实现New方法,另一个实现通过Driver的某个子类实现.
问题是通过实现接口我必须返回'Driver',但有时我想返回'SubclassOfDriver'.我可以说你应该把结果转换成你想要的驱动程序,但这是不安全的,并且编码器需要有关实现的信息以确定哪个驱动程序已被实例化.这样做的最佳方法是什么?
谢谢
您可以使用显式接口实现有效地重载返回类型:
Driver IDriverService.New()
{
return New(); // Calls the method below
}
public SubclassOfDriver New()
{
return new SubclassOfDriver();
}
Run Code Online (Sandbox Code Playgroud)
现在任何只知道你的实现作为接口实现的代码都会看到显式接口实现方法,并期望返回类型为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();
Run Code Online (Sandbox Code Playgroud)
或者,您可能希望使您的界面通用:
public interface IDriverFactory<TDriver> where TDriver : Driver
{
TDriver New();
}
public class SpecialDriverFactory : IDriverFactory<SubclassOfDriver>
{
public SubclassOfDriver New()
{
return new SubclassOfDriver();
}
}
Run Code Online (Sandbox Code Playgroud)