猿问

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

它正在工作,但不是动态的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...

    }

}

在启动.cs


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


犯罪嫌疑人X
浏览 485回答 2
2回答

芜湖不芜

我已更改为:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Type genericClass = typeof(CustomRepository<>).MakeGenericType(_typeObject);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var invokeObject = validationContext.GetService(genericClass);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var parameters = new object [] { value, "username" };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MethodInfo method = genericClass.GetMethod("IsValid");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; object getCheck = method.Invoke(invokeObject, parameters);
随时随地看视频慕课网APP
我要回答