如何将类型动态传递给 Activator.CreateInstance(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
{}

我的classCustomerAssociation是:

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);

然后出现运行时错误,

Unable to cast object of type 'CustomerAssociation' to type 'INewReleaseValidationRule`1[ForecastEstimateViewModel]'.

代码中的实际意图有点不清楚,但您可以尝试调整验证器的 运行 方法以采用如下泛型类型:

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);