[英]How to pass object[] to Activator.CreateInstance(type, params object[])
[英]How to pass type dynamically to Activator.CreateInstance(object)?
我正在尝试使用Activator.CreateInstace()
实现通用解决方案
我下面有界面
public interface INewReleaseValidationRule<T> where T : INewReleaseValidationEntity
{
void Run(CtxNewRelease ctx, IEnumerable<T> entities);
string GetMessage(string messageName, string fallbackMessage);
}
public interface INewReleaseValidationEntity
{}
我的类CustomerAssociation
是:
public class CustomerAssociation : INewReleaseValidationEntity
{
public void Run(Context.Ctx context, IList<INewReleaseValidationEntity> entitiesObject)
{}
}
然后我有一个视图模型,它也在实现INewReleaseValidationEntity
。
public class ForecastViewModel : INewReleaseValidationEntity
{
}
然后,
public partial class ValidationRule
{
public void Run(Ctx context, List<ForecastViewModel > entity)
{
var validation = this.GetExecutionType();
var execution = (INewReleaseValidationRule<entity>)Activator.CreateInstance(validation);
execution.Run(context, entity.ToArray());
}
}
在上面突出显示的语句中,我遇到了错误。
如果我用
var execution = (CustomerAssociation)Activator.CreateInstance(validation);
然后就可以正常工作了。 但是我想动态提供显式类型(在这种情况下为CustomerAssociation
)。
我所有的显式类型(即CustomerAssociation
)和其他类型都将从INewReleaseValidationRule<T>
继承。
如果我写
var execution = (INewReleaseValidationRule<ForecastViewModel>)Activator.CreateInstance(validation);
然后出现运行时错误,
无法将类型为“ CustomerAssociation”的对象转换为类型为“ INewReleaseValidationRule`1 [ForecastEstimateViewModel]”。
从代码中还不清楚实际意图是什么,但是您可以尝试调整验证器的run方法以采用如下通用类型:
public partial class ValidationRule
{
public void Run<T>(Ctx context, List<ForecastViewModel> entity)
where T : class, INewReleaseValidationEntity
{
var execution = (T)Activator.CreateInstance<T>();
execution.Run(context, entity.ToArray());
}
}
并这样称呼它:
new ValidationRule().Run<CustomerAssociation(context, entities);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.