这是我的代码
class InternalDevice1
{
}
class InternalDevice2
{
}
class SpecificDevice1 : InternalDevice1
{
}
class SpecificDevice2 : InternalDevice2
{
}
class SpecificDevice3 : InternalDevice1
{
}
class SpecificDevice4 : InternalDevice2
{
}
class MyWholeDevice1 : IDevice
{
MyWholeDevice(SpecificDevice1 device1, SpecificDevice2 device2) { }
SpecificDevice1 Device { get; }
}
class MyWholeDevice2 : IDevice
{
MyWholeDevice(SpecificDevice3 device1, SpecificDevice4 device2) { }
SpecificDevice3 Device { get; }
}
interface IDevice
{
InternalDevice1 Device { get; }
}
问题是IDevice中的返回类型是InternalDevice1(更通用) 虽然我需要SpecificDevice(仍然从InternalDevice中删除) 我在尝试使用它时遇到了一个问题:
IDevice = new MyWholeDevice ...
答案 0 :(得分:0)
您应该设置IDevice generic
interface IDevice<TDevice>
where TDevice : InternalDevice1
{
TDevice Device { get; }
}
然后你的课程将如下所示:
class MyWholeDevice1 : IDevice<SpecificDevice1>
{
MyWholeDevice(SpecificDevice1 device1, SpecificDevice2 device2) { }
SpecificDevice1 Device { get; }
}
class MyWholeDevice2 : IDevice<SpecificDevice3>
{
MyWholeDevice(SpecificDevice3 device1, SpecificDevice4 device2) { }
SpecificDevice3 Device { get; }
}