0

假设我有两个接口, 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类中获取设置。

4

4 回答 4

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();
    }
}
于 2013-10-04T06:24:02.610 回答
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 
于 2013-10-04T06:30:34.177 回答
1

使 DeviceSettings 成为一个抽象类

于 2013-10-04T06:24:18.790 回答
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
于 2013-10-04T07:13:52.840 回答