DataAnnotations似乎无法使用Validator在值类型上正常运行

Per*_*der 0 c# data-annotations

为什么这总是回归真的?

 class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Age = 24;

            ICollection<ValidationResult> results = new Collection<ValidationResult>();
            bool isValid = Validator.TryValidateObject(p, new ValidationContext(p, null, null), results);

            Console.WriteLine("Valid = {0}",isValid);

            foreach (var result in results)
            {
                Console.WriteLine(result.ErrorMessage);
            }

            Console.ReadKey();
        }
    }

    public class Person
    {
        [Required(ErrorMessage = "You have to identify yourself!!")]
        public int Id { get; set; }

        public decimal Age { get; set; }    

    }
Run Code Online (Sandbox Code Playgroud)

我的用法有什么问题?

SLa*_*aks 7

int是一种值类型,永远不可能null.

new Person()将具有Id0,这将满足[Required].
通常,[Required]对值类型没用.

要解决此问题,您可以使用可空的int?.