简体   繁体   English

使用C#,如何将return语句注入方法?

[英]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: 这是我希望完成的工作:

What I have 我有的

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 would like to have 我想拥有什么

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: 多亏了以上评论的帮助,我产生了以下代码,该代码完全符合我的要求:

The Extension Method: 扩展方法:

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);
            }
        }

Usage 用法

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.

相关问题 如何在C#IF语句中使用此示例“ return”? - How do I make use of this examples “return”, in a C# IF statement? 怎么做 Java 中的 C# return 语句 - How to do this C# return statement in Java 我在此方法C#中返回什么 - What do i return in this method c# C#: How do I use a method, check if return is null, and set value in one line using lambda and C# Null Propagation - C#: How do I use a method, check if return is null, and set value in one line using lambda and C# Null Propagation 如何在C#中的内联SQL语句的插入语句之后返回新创建的ID? - How do I return the newly created ID after an insert statement from an inline SQL statement in C#? 如何使用Update方法中的if语句将新图像添加到XNA C#中已经在运行的游戏的窗口中? - How do I add a new image to the window of an already running game in XNA C# using an if statement in the Update method? 如何从c#中的方法中的for语句返回值 - How to return a value from a for statement in a method in c# 如何使我的通用方法成为一种使用 C# 从 mongoDB 返回的列的方法? - How do I make my generic method a way to choose which columns to return from mongoDB using C#? 如何使用Dllimport在C#中调用此Delphi方法? - How do I call this Delphi method in C# using Dllimport? 如何在C#中将SELECT COUNT语句的结果作为字符串返回? - How do I return the result of a SELECT COUNT statement as a string in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM