C# [Required()] 注释在应该抛出异常时不抛出异常
C# [Required()] annotation doesn't throw exception when it should
我在 属性 上方使用 class:
中的 [Required()]
public class A
{
[Required()]
public string Str { get; set; }
public int Salary { get; set; }
}
在 Main() 中,我创建了一个 class 的实例,
不设置 属性:
static void Main(string[] args)
{
A a = new A();
}
我预计会出现异常,因为我没有设置任何值
到 Str 属性,但我没有得到。
我错过了 [Required] 的目的吗?
Required
属性用于验证(例如在 ASP.NET 中),而不是用于抛出运行时异常。
Did I miss the purpose of [Required]?
非常喜欢。让我们阅读 the docs:
The RequiredAttribute
attribute specifies that when a field on a form is validated, the field must contain a value
所以我们专门讨论验证:它是 System.ComponentModel.DataAnnotations
命名空间中各种 classes 的一部分,主要与验证有关。
原则上,请查看 Validation
class,它允许您根据您赋予对象的属性验证对象的属性。这个基础设施被用在很多地方,比如 ASP.NET,或者 EF.
我在 属性 上方使用 class:
中的 [Required()]public class A
{
[Required()]
public string Str { get; set; }
public int Salary { get; set; }
}
在 Main() 中,我创建了一个 class 的实例, 不设置 属性:
static void Main(string[] args)
{
A a = new A();
}
我预计会出现异常,因为我没有设置任何值 到 Str 属性,但我没有得到。 我错过了 [Required] 的目的吗?
Required
属性用于验证(例如在 ASP.NET 中),而不是用于抛出运行时异常。
Did I miss the purpose of [Required]?
非常喜欢。让我们阅读 the docs:
The
RequiredAttribute
attribute specifies that when a field on a form is validated, the field must contain a value
所以我们专门讨论验证:它是 System.ComponentModel.DataAnnotations
命名空间中各种 classes 的一部分,主要与验证有关。
原则上,请查看 Validation
class,它允许您根据您赋予对象的属性验证对象的属性。这个基础设施被用在很多地方,比如 ASP.NET,或者 EF.