当我尝试使用带有数据注释的元数据类注册提供程序时,当我使用对象实例而不是类型时,我无法使验证器正常工作。
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
public class Program
{
public static void Main()
{
/* Should not pass validation */
var obj = new MyClass()
{Value = "123456"};
/* Should pass validation */
var obj2 = new MyClass()
{Value = "123456"};
/* Add custom provider to just the first object */
var provider = new AssociatedMetadataTypeTypeDescriptionProvider(typeof (MyClass), typeof (MyClassMeta));
TypeDescriptor.AddProvider(provider, obj);
Console.WriteLine("obj:");
Validate(obj);
Console.WriteLine("obj2:");
Validate(obj2);
}
private static void Validate(object obj)
{
ValidationContext context = new ValidationContext(obj, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(obj, context, results, true);
if (!valid)
{
foreach (ValidationResult vr in results)
{
Console.Write("Member Name:{0}", vr.MemberNames.First());
Console.WriteLine(" - {0}", vr.ErrorMessage);
}
}
else
{
Console.WriteLine("I am valid.");
}
}
}
public class MyClass
{
[Required]
public string Value
{
get;
set;
}
}
public class MyClassMeta
{
[MaxLength(5)]
public string Value
{
get;
set;
}
}
https://dotnetfiddle.net/RlOuTg
我希望将元数据类验证器应用于“ obj”,但是当我运行此代码时它仍然有效。如果我更改代码以使用类型而不是对象,则将验证器应用于该类型的所有实例(按预期方式)。我想在运行时将元数据应用于对象的特定实例。