假设我有两个接口,
Device
和DeviceSettings
,
然后我上课了:
class DevA : Device
class DevASettings : DeviceSettings
class DevB : Device
class DevBSettings : DeviceSettings
class DevC : Device
class DevCSettings : DeviceSettings
在Device
接口中,有两个函数叫做:
DeviceSettings GetSettings();
void SetSettings( DeviceSettings setting);
示例:
DevA.GetSettings()
可以从DevASettings
现在我想将DeviceSettings
从接口更改为基类。
并且仍然想要使用例如DevA.GetSettings()
可以从DevASetting
然后如何在Device
中进行更改:
例如如何更改以上两个函数调用,以便Device
可以从DeviceSettings
类中获取设置。
答案 0 :(得分:3)
您可以像这样制作设备界面
interface Device<T> where T:DeviceSettings
{
T GetDevice();
void SerDevice(T settings);
}
class DeviceA:Device<DeviceASettings>
{
public DeviceASettings GetDevice()
{
throw new NotImplementedException();
}
public void SerDevice(DeviceASettings settings)
{
throw new NotImplementedException();
}
}
答案 1 :(得分:2)
我实际上将Device
变成了一个抽象类:
public abstract class Device
{
DeviceSettings deviceSettings;
DeviceSettings GetSettings()
{
return this.deviceSettings;
}
void SetSettings(DeviceSettings setting)
{
this.deviceSettings = setting;
}
}
public class DevA : Device
{
public DevA()
{
this.deviceSettings = new DevASettings();
}
//Do what you need with deviceSettings here
}
//Repeat for DevB/DevBSettings and DevC/DevCSettings
答案 2 :(得分:1)
使DeviceSettings成为一个抽象类
答案 3 :(得分:0)
使用属性更改实现。我没有看到基类的问题或用它的派生类替换它。根据您的需要进行更改。
interface IDevice
{
DeviceSettingsBase DeviceSetting { get; set; }
}
class DeviceSettingsBase
{
public virtual void DeviceSettingsName()
{
Console.WriteLine("DeviceSettingsBase");
}
}
class DevA : IDevice
{
public DeviceSettingsBase DeviceSetting { get; set; }
}
class DevASettings : DeviceSettingsBase
{
public override void DeviceSettingsName()
{
Console.WriteLine("DevASettings");
}
}
class DevBSettings : DeviceSettingsBase
{
public override void DeviceSettingsName()
{
Console.WriteLine("DevBSettings");
}
}
public static class Example
{
public static void Main()
{
DevA devA = new DevA();
devA.DeviceSetting = new DevASettings();
devA.DeviceSetting.DeviceSettingsName();
devA.DeviceSetting = new DevBSettings();
devA.DeviceSetting.DeviceSettingsName();
devA.DeviceSetting = new DeviceSettingsBase();
devA.DeviceSetting.DeviceSettingsName();
}
}
<强>输出强>
DevASettings
DevBSettings
DeviceSettingsBase