![](/img/trans.png)
[英]Using Abstract class with Generic parameters in INotifyPropertyChanged object
[英]Convert object to generic abstract class
我來到這里的是一個像這樣的課程:
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 }); ;
}
}
但這是一個整潔的設計嗎?
對於SIBRegisterHardware2
類型,應使用接口而不是抽象類。 然后,您可以在泛型中使用協方差 :
public interface IDevice { }
public interface IDeviceA : IDevice { }
public interface IDeviceB : IDevice { }
public interface ISIBRegisterHardware2<out T> where T : class, IDevice
{
void DoSomething();
}
internal class DeviceA : ISIBRegisterHardware2<IDeviceA>
{
//...
}
internal class DeviceB : ISIBRegisterHardware2<IDeviceB>
{
//...
}
if (createDevA == true)
{
ISIBRegisterHardware2<IDevice> devHandle = new DeviceA();
}
else
{
ISIBRegisterHardware2<IDevice> devHandle = new DeviceB();
}
更新0
public interface ISIBRegisterHardware2<out T> : Register.IRegisterHardware<UInt16, UInt16> where T : class, IDevice
{
T Open();
}
public abstract class SIBRegisterHardware2<T> : ISIBRegisterHardware2<T> where T : class, IDevice
{
T ISIBRegisterHardware2<T>.Open()
{
return OpenInternal();
}
protected virtual T OpenInternal()
{
//Common logic to open.
}
}
internal class DeviceA : SIBRegisterHardware2<IDeviceA>
{
//...
}
internal class DeviceB : SIBRegisterHardware2<IDeviceB>
{
//...
}
ISIBRegisterHardware2<IDevice> devHandle;
if (createDevA == true)
{
devHandle = new DeviceA();
}
else
{
devHandle = new DeviceB();
}
devHandle.Open();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.