数据注释仅在对字段使用 get 访问器时验证

Data Annotation only validates when using get accessor on field

在验证数据注释时,为什么它似乎只有在您要验证的 属性 上使用 get 访问器时才能(正确)验证?

在下面的示例中,Name 属性 将始终被视为有效,即使它未分配,但 Address 属性 将仅被视为有效如果它分配了一个非空字符串值,都是因为它使用了 get 访问器。这是为什么?

当然 TryValidateObject 基本上只会使用 test.Address 来访问值,无论它是否通过 get 访问器。

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();
        var _errors = new List<ValidationResult>();

        bool isValid = Validator.TryValidateObject(
            test, new ValidationContext(test), _errors, true);
    }
}

public class Test
{
    [Required]
    public string Name; // Returns true even when unassigned / null / empty string

    [Required]
    public string Address { get; } // Only returns true when assigned a non-empty string
}

原因是Validator.TryValidateObject只会检查属性和class级别的注解,但是你的Name是一个字段,不是一个属性(请参阅 here Validator class 的文档未提及字段)。如果您将任何其他属性(如 Range)应用于字段 - 它也不会与 Validator.TryValidateObject 一起使用。 RequiredAttribute 可以应用于字段的原因是因为 RequiredAttribute 本身就是一个实体,而不是 related\tied 以任何方式验证器 class。任何其他验证机制 可以 验证 public 字段,它只是特定的 Validator class 而不是。