[英]Using C#, how do I inject a return statement into a method?
Thanks for looking, I realize the question is a bit odd. 感谢您的关注,我意识到这个问题有点奇怪。 Here is what I am hoping to accomplish: 这是我希望完成的工作:
I am using System.ComponentModel.DataAnnotations
to validate a model that has been posted from a web page. 我正在使用System.ComponentModel.DataAnnotations
来验证已从网页发布的模型。 I have already partially abstracted the necessary code into a shared method: 我已经将必要的代码部分抽象为共享方法:
public static string Create_Widget(WidgetModel postedWidget)
{
//Validate the model
var errors = HelperMethods.Validate(postedWidget);
if (!string.IsNullOrEmpty(errors))
{
return errors;
}
//Do other stuff
}
And the helper method: 和辅助方法:
public static string Validate<T>(T entity)
{
var context = new ValidationContext(entity, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(entity, context, results);
return string.Join(",", results.Select(s => s.ErrorMessage));
}
What I really want to do is just have an extension method to validate my model with out adding an if statement
beneath it for the conditional return: 我真正想做的只是有一个扩展方法来验证我的模型,而无需在条件下为条件返回添加if statement
:
public static string Create_Widget(WidgetModel postedWidget)
{
//Validate the model
postedWidget.Validate(); //Automatically returns error string if errors.
//Do other stuff
}
Is this possible? 这可能吗?
Thanks to the help from the comments above, I produced the following code which does exactly as I wanted: 多亏了以上评论的帮助,我产生了以下代码,该代码完全符合我的要求:
public static void Validate<T>(this T entity)
{
var errors = new List<ValidationResult>();
var result = "";
try
{
var context = new ValidationContext(entity, null, null);
Validator.TryValidateObject(entity, context, errors, true);
result = (errors.Any()) ? string.Join(",", errors.Select(s => s.ErrorMessage)) : "";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
if (!string.IsNullOrEmpty(result))
{
throw new Exception(result);
}
}
Assuming you have a valid model with data validation annotations, all you need is this: 假设您有一个带有数据验证批注的有效模型,那么您需要做的就是:
widgetModel.Validate();
If one or more properties within your model don't clear validation, a comma delimited list of errors is returned. 如果模型中的一个或多个属性未清除验证,则会返回以逗号分隔的错误列表。 In my case, I am using AngularJS in the view so I can use .error()
to catch failed api calls and use the list of errors in the view. 就我而言,我在视图中使用AngularJS,因此可以使用.error()
捕获失败的api调用并在视图中使用错误列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.