[英]How to pass in a list of generic objects into a method?
My CheckModelValidation
method (that tests a single model) tests out fine in my unit test just by passing in the class model UserInsertModel
as an object but when I try to pass in a list of models to CheckModelListValidation
in my unit test, it tells me it's an unknown method
(because it doesn't like what I'm trying to pass in - which is a List<UserInsertModel>
). 我的CheckModelValidation
方法(测试单个模型)仅通过将类模型UserInsertModel
作为对象传入,而在我的单元测试中进行了很好的测试,但是当我尝试在我的单元测试CheckModelListValidation
模型列表传递给CheckModelListValidation
时,它告诉我它是一个unknown method
(因为它不喜欢我要传递的内容-这是List<UserInsertModel>
)。
Is there a better way to do this using generics (which I've just recently gotten into)? 有没有更好的方法可以使用泛型(我最近刚接触过)?
public class ValidationManager
{
public static void CheckModelListValidation(List<object> model)
{
string errorMessages = "";
int iCnt = 0;
foreach (var u in model)
{
iCnt += 1;
string itemErrors = ValidateModel(u);
if (!string.IsNullOrEmpty(itemErrors))
{
errorMessages = string.Format("Item {0} errors: {1}", iCnt, itemErrors);
}
}
if (!string.IsNullOrEmpty(errorMessages))
{
throw new Exception(errorMessages);
}
}
public static void CheckModelValidation(object model)
{
string errorMessages = ValidateModel(model);
if (!string.IsNullOrEmpty(errorMessages))
{
throw new Exception(errorMessages);
}
}
private static string ValidateModel(object model)
{
string errorMessages = "";
List<ValidationResult> validationResults = new List<ValidationResult>();
ValidationContext valContext = new ValidationContext(model, null, null);
bool isValid = Validator.TryValidateObject(model, valContext, validationResults, true);
if (!isValid)
{
errorMessages= string.Format("Errors: {0}", String.Join("; ", validationResults.Select(v => v.ErrorMessage).ToArray()));
}
return errorMessages;
}
}
And here's my implementation: 这是我的实现:
UserInsertModel model = new UserInsertModel();
model.EmailAddress = "test";
List<UserInsertModel> models = new List<UserInsertModel>();
models.Add(model);
models.Add(model);
ValidationManager.CheckModelListValidation(models);
You can make your validation class generic: 您可以使您的验证类通用:
public class ValidationManager<T>
{
// Change methods to accept T instead of object
public static void CheckModelListValidation(List<T> model)
{
//...
public static void CheckModelValidation(T model)
{
// etc
将方法的签名更改为:
public static void CheckModelListValidation<T>(List<T> model)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.