[英]How to pass type dynamically to Activator.CreateInstance(object)?
I am trying to implement generic solution using Activator.CreateInstace()
我正在尝试使用Activator.CreateInstace()
实现通用解决方案
Below I have interface, 我下面有界面
public interface INewReleaseValidationRule<T> where T : INewReleaseValidationEntity
{
void Run(CtxNewRelease ctx, IEnumerable<T> entities);
string GetMessage(string messageName, string fallbackMessage);
}
public interface INewReleaseValidationEntity
{}
My class CustomerAssociation
is: 我的类CustomerAssociation
是:
public class CustomerAssociation : INewReleaseValidationEntity
{
public void Run(Context.Ctx context, IList<INewReleaseValidationEntity> entitiesObject)
{}
}
Then I have view model which is also implementing INewReleaseValidationEntity
. 然后我有一个视图模型,它也在实现INewReleaseValidationEntity
。
public class ForecastViewModel : INewReleaseValidationEntity
{
}
Then, 然后,
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());
}
}
In above highlighted statement I am getting error. 在上面突出显示的语句中,我遇到了错误。
If I use, 如果我用
var execution = (CustomerAssociation)Activator.CreateInstance(validation);
then it works perfectly fine. 然后就可以正常工作了。 But I want to provide the explicit type (in this case CustomerAssociation
) dynamically. 但是我想动态提供显式类型(在这种情况下为CustomerAssociation
)。
All my explicit type (that is CustomerAssociation
) and others will be inherited from INewReleaseValidationRule<T>
. 我所有的显式类型(即CustomerAssociation
)和其他类型都将从INewReleaseValidationRule<T>
继承。
If I write 如果我写
var execution = (INewReleaseValidationRule<ForecastViewModel>)Activator.CreateInstance(validation);
then getting runtime error, 然后出现运行时错误,
Unable to cast object of type 'CustomerAssociation' to type 'INewReleaseValidationRule`1[ForecastEstimateViewModel]'. 无法将类型为“ CustomerAssociation”的对象转换为类型为“ INewReleaseValidationRule`1 [ForecastEstimateViewModel]”。
It's a bit unclear from the code what the actual intent is, but you can try adjusting your validator's run method to take a generic type like this: 从代码中还不清楚实际意图是什么,但是您可以尝试调整验证器的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());
}
}
And call it like this: 并这样称呼它:
new ValidationRule().Run<CustomerAssociation(context, entities);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.