Reflection方法调用对象与目标类型不匹配

时间:2018-05-29 21:29:40

标签: c# asp.net-core

它正在运作,但as CustomRepository<ApplicationUser>不是动态的:

public class CheckUnique : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        Type genericClass = typeof(CustomRepository<>).MakeGenericType(typeof(ApplicationUser));

        var xx = validationContext.GetService(genericClass) as CustomRepository<ApplicationUser>;

        var res = xx.IsValid(value, "username");
        if (!res)
        {
            return new ValidationResult("exist", new[] { "name" });
        }
        else
        {
            return null;
        }
    }
}

我想使用反射或其他方式将此as CustomRepository<ApplicationUser>更改为某些人。如果不是,我应该使用许多不同的验证来检查唯一值..

当我尝试使用时:

        MethodInfo method = genericClass.GetMethod("IsValid");
        object params = new object [] { value, "username" };
        object val = method.Invoke(this, params );

我收到错误 - 对象与目标类型不匹配,并且没有找不到原因。

一些来自 CustomRepository.cs

public class CustomRepository<T> where T : class
{
    private readonly AppDbContext _appDbContext;
    public CustomRepository(AppDbContext appDbContext)
    {
        _appDbContext = appDbContext;
    }

    public bool IsValid(object value, string prop)
    {
      business logic...
    }
}

Startup.cs

  services.AddScoped(typeof(CustomRepository<>));

2 个答案:

答案 0 :(得分:0)

第一个参数应该是MethodInfo所属类型的实例 - CustomRepository<ApplicationUser>。您正在通过CheckUnique

所以而不是

object val = method.Invoke(this, params );

object val = method.Invoke(xx, params );

答案 1 :(得分:0)

感谢John Wu

我已改为:

            Type genericClass = typeof(CustomRepository<>).MakeGenericType(_typeObject);
            var invokeObject = validationContext.GetService(genericClass);

            var parameters = new object [] { value, "username" };
            MethodInfo method = genericClass.GetMethod("IsValid");
            object getCheck = method.Invoke(invokeObject, parameters);