我有一个类型objDataModel
的变量UDataModel
,它继承自AbstractDataModel
public class AbstractDataModel
{
internal string SomeName { get; set; }
}
public class UDataModel: AbstractDataModel
{
}
public class FDataModel: AbstractDataModel
{
}
public class UCommandProcessor : AbstractCommandProcessor<UDataModel>
{
}
public class FCommandProcessor : AbstractCommandProcessor<FDataModel>
{
}
public abstract class AbstractCommandProcessor<TDataModel> :SomeInterface<TDataModel>
where TDataModel: AbstractDataModel
{
}
我有UDataModelType类型的变量,即。var tDataModelType= typeOf(UDataModel)
使用它我可以创建它的对象。
var tDataModel = (AbstractDataModel)Activator.CreateInstance(tDataModelType);
我有UCommandProcessor类型的变量,即var processorType= typeOf(UCommandProcessor)
我能够创建
var processor = Activator.CreateInstance(processorType);
但我无法将其输入到UCommandProcessor中 我试过的时候
var processor = (AbstractCommandProcessor<AbstractDataModel>)Activator.CreateInstance(processorType);
我的例外是
无法转换类型&#39; ABC.Domain.UCommandProcessor&#39;的对象输入 &#39; ABC.Common.Contract.AbstractCommandProcessor`1 [ABC.Common.Contract.AbstractDataModel]&#39;
有没有像
这样的方法 var processor = (AbstractCommandProcessor<typeOf(tDataModel )>)Activator.CreateInstance(processorType);
即使我不喜欢
var processor = (AbstractCommandProcessor<typeOf(tDataModel )>)Activator.CreateInstance(processorType);
答案 0 :(得分:2)
强制转换无法工作,如果转换为AbstractCommandProcessor<AbstractDataModel>
,则基本上需要协方差,这仅适用于接口和委托。在这一行:
(AbstractCommandProcessor<AbstractDataModel>)Activator.CreateInstance(processorType);
演员也可能是AbstractCommandProcessor<FDataModel>
,显然无效。我建议创建一个抽象类AbstractCommandProcessor
,从中派生通用版本,然后你可以转换为非泛型版本:
public abstract class AbstractCommandProcessor {}
public class AbstractCommandProcessor<T> : AbstractCommandProcessor, SomeInterface<T>
where T: AbstractDataModel
...
var processor = (AbstractCommandProcessor)Activator.CreateInstance(processorType);
编辑:如果您真的不需要课程,可以使用界面和协方差:
public interface AbstractDataModel { }
public class UDataModel : AbstractDataModel { }
public class FDataModel : AbstractDataModel { }
public class UCommandProcessor : AbstractCommandProcessor<UDataModel> { }
public class FCommandProcessor : AbstractCommandProcessor<UDataModel> { }
public interface AbstractCommandProcessor<out TDataModel> : SomeInterface<TDataModel>
where TDataModel : AbstractDataModel
{ }
public interface SomeInterface<out TDataModel> where TDataModel : AbstractDataModel { }
...
var processor =
(AbstractCommandProcessor<AbstractDataModel>)Activator.CreateInstance(processorType);
这将因协方差而起作用(out
关键字意味着您可以使用比泛型约束指定的更多派生的东西。)