它正在工作,但不是动态的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.cspublic 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<>));
2 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
我已更改为:
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);
- 2 回答
- 0 关注
- 484 浏览
添加回答
举报
0/150
提交
取消