我來到這裏的一類,看起來像這樣:轉換對象一般抽象類
public abstract class SIBRegisterHardware2<T> : Register.IRegisterHardware<UInt16, UInt16> where T : IDevice
{
protected T open()
{
// connect to server and return device T
}
// ..
}
public class Device : SIBRegisterHardware2<IDevice>
{
// ..
}
和一些派生類:
internal class DeviceA: SIBRegisterHardware2<IDeviceA>
{
}
internal class DeviceB: SIBRegisterHardware2<IDeviceB>
{
}
現在我要尋找一個解決方案,使我這個:
if(createDevA == true) {
Device<IDevice> devHandle = new DeviceA();
} else {
Device<IDevice> devHandle = new DeviceB():
}
事情是這樣的代碼產生錯誤這樣的:
Cannot implicitly convert type 'DeviceA' to 'SIBRegisterHardware2<IDevice>'
有沒有一種方法可以讓我抽象出這樣的模板?
東西我嘗試了創造了另一類與反思工作:
public class DeviceX : SIBRegisterHardware2<IDevice>
{
private Register.IRegisterHardware<UInt16, UInt16> device = null;
private Type deviceType = null;
public DeviceX (String hwInterfaceClassName)
{
if (hwInterfaceClassName.Equals("DeviceA")) {
device = new DeviceA();
deviceType = device.GetType();
}
else if (hwInterfaceClassName.Equals("DeviceB")) {
device = new DeviceB();
deviceType = device.GetType();
}
}
public override String doSomething(int param)
{
return (String)deviceType.GetMethod("doSomething").Invoke(device, new object[] { param }); ;
}
}
而且是一個利落的設計?
'DeviceA'和'DeviceB'不是從'Device'的。此外,'Device'不是通用類型,您不能寫'Device'。我錯過了什麼嗎? –
Dennis
感謝您的提示。我添加了一個缺失的類.. – displayname