简体   繁体   English

[必需]做什么?

[英]What does [Required] do?

I found nothing on the web what [Required] actually does. 我在网上没有发现[Required]的实际功能。 The msdn-article is not explorative at all. msdn-article根本不是探索性的。

static class Program
{
    public static Main()
    {
        var vustomer = new CustomerClass();
    }
}

public class CustomerClass
{
    public string m_FirstName;
    [Required]
    public string m_LastName;
}

As far as i understand, that should throw an exception since m_LastName is required, but not set. 据我了解,这应该引发异常,因为m_LastName是必需的,但未设置。 But i don't get one. 但是我没有。 I don't get what it's good for and what this actually does. 我不知道这有什么好处,实际上没有做。

RequiredAttribute , like all other attributes, does nothing by itself other than annotate something (in this case, a field of a type). 与所有其他属性一样, RequiredAttribute除了注释某些内容(在这种情况下,是类型的字段)之外,本身不会执行任何操作。 It is entirely up to the application that consumes the type to detect the presence of the attribute and respond accordingly. 完全由使用该类型的应用程序来检测属性的存在并做出相应的响应。

Your sample program does not do this, so the attribute does not have any visible effect. 您的示例程序不会执行此操作,因此该属性没有任何可见的效果。 Certain frameworks such as ASP.NET MVC and WPF do check for and respond to the presence of the attribute. 诸如ASP.NET MVC和WPF之类的某些框架检查并响应该属性的存在。

This attribute is used by the Validator class to add validation errors based on any types that inherit from ValidationAttribute . Validator类使用此属性添加基于从ValidationAttribute继承的任何类型的验证错误。 This is used by MVC model validation , for example. 例如,这可用于MVC模型验证

Documentation on RequiredAttribute : 有关RequiredAttribute文档:

Specifies that a data field value is required. 指定需要一个数据字段值。

However this validation is typically only performed in the UI layer. 但是,此验证通常仅在UI层中执行。 It is not "baked" into the constructor or other low-level usage. 它不会“烘焙”到构造函数或其他低级用法中。 If you want to manually fire the validation you could do something like: 如果您想手动触发验证,则可以执行以下操作:

var customer = new CustomerClass();
var context = new ValidationContext(customer, serviceProvider: null, items: null);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(customer, context, results);

if (!isValid)
{
    foreach (var validationResult in results)
    {
        Console.WriteLine(validationResult.ErrorMessage);
    }
}

To add to the current answers, these are some of the practical uses I can think of out of my head: 为了增加当前的答案,以下是一些我可以想到的实际用途:

  • Entity Framework use this to model the database as not nullable fields. 实体框架使用它来将数据库建模为不可为空的字段。
  • Javascript client side validation provides javascript libraries for checking if the input field has any data, else prevent the form submission avoiding unnecesary roundtrips to the server. Javascript客户端验证提供了JavaScript库,用于检查输入字段中是否有任何数据,否则阻止表单提交,从而避免不必要的服务器往返。
  • Server side validation (when doing model binding) also check when you are posting a model with that decorator that the attribute passed in is in the request. 服务器端验证(在执行模型绑定时)还会检查何时使用该装饰器发布模型,而该装饰器中传入的属性在请求中。 This determines if the model state should be set to an invalid state or not. 这确定是否应将模型状态设置为无效状态。 (1) (1)
  • There are also annotation for JSON.NET library that changes how the model is serialized/unserialized. JSON.NET库也有注释,它可以更改模型的序列化/反序列化方式。 I'm pretty confident (but not sure) that the Validate Schema of Json.net does take into consideration the 'Required' attribute when validating a schema. 我非常有信心(但不确定),Json.net的“验证模式”在验证模式时确实考虑了“ Required”属性。
  • Other attribute decorators are used on web services, but 'Required' is not one I know has it uses in this scenario. Web服务上使用了其他属性装饰器,但是在这种情况下,“必需”不是我所知道的。
  • Web api uses this attribute to mark the property as required on documentation help pages and model binding. Web api使用此属性将属性标记为文档帮助页面和模型绑定所要求的。
  • You can create your own application logic that can be aware of the 'Required' property. 您可以创建自己的应用程序逻辑,以了解“ Required”属性。 For example, on a view to mark the property with an * in the label if it's required. 例如,在需要标记的视图上用*标记属性的视图。

This are some uses but you are not limited to them. 这是一些用途,但您不仅限于此。

(1) Note: if your property is, for example, an int and you decorate it with Required, model state will never be on a invalid state. (1) 注意:例如,如果您的属性是一个int并用Required进行装饰,则模型状态永远不会处于无效状态。 You should use Nullable properties for this use-cases. 对于此用例,应使用Nullable属性。

In C#, attributes are almost decoration to classes and properties. 在C#中,属性几乎是对类和属性的修饰。

Except for a few security related attributes, most do nothing. 除了一些与安全性相关的属性外,大多数属性什么都不做。 They are used by a higher-level framework to do something. 它们被更高级别的框架用来做某事。

In the case of ASP.NET 4 MVC, only when the object is part of a request that attribute is used to generate an error. 对于ASP.NET 4 MVC,仅当对象是请求的一部分时,该属性才用于生成错误。

If you want to use that attribute in any other environment, you must write code to inspect it. 如果要在任何其他环境中使用该属性,则必须编写代码进行检查。

It won't do anything from a plain old public static void Main() 它不会从普通的旧public static void Main()做任何事情

Specifies that a data field value is required. 指定需要一个数据字段值。

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx http://msdn.microsoft.com/zh-CN/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx

There are several attribute properties that can manipulate how this attribute is applied. 有几个属性可以控制如何应用此属性。

There's a MSDN article that talks about how to use validation attributes to annotate your object models. MSDN上有一篇文章讨论了如何使用验证属性来注释对象模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM