如何使用自定义类型的标准验证数据注释?

How to use standard validation data annotations with custom types?

是否可以将 .NET 框架内的标准数据注释(例如 StringLength、RegularExpression、Required 等)与自定义类型一起使用?

我想做的是这样的:

  class MyProperty<TValue>
   {
      public bool Reset { get; set; }
      public TValue Value { get; set; }
   }

   class MyClass
   {
      [Required]
      [StringLength(32)]
      MyProperty<string> Name { get; set; }

      [StringLength(128)]
      MyProperty<string> Address { get; set; }

   }

当然,我希望验证作用于 "Value" 属性。查看各种验证属性的代码,它们似乎只是调用 ToString() 以从对象中获取值。我尝试将 ToString() 和 return Value 重写为字符串,但抛出了异常,指出注释无法将对象 (Value) 转换为字符串(即使重写只是那样......?)。 =11=]

我试图避免编写所有各种可能的验证器的自定义版本来适应这种简单类型。

您可以查看 StringLength 的源代码: https://github.com/Microsoft/referencesource/blob/master/System.ComponentModel.DataAnnotations/DataAnnotations/StringLengthAttribute.cs

您可以看到 IsValid 将您的值转换为字符串,这对于您的自定义 class 会失败。但是您可以创建自己的验证属性。

这是一个显式的字符串转换选项,用于不编写您自己的验证器:

public static explicit operator string(MyProperty prop)
{
       return "Stuff you want to return as string";
}

将其放入您的 MyProperty class。