代码之家  ›  专栏  ›  技术社区  ›  Jake Shakesworth

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

  •  1
  • Jake Shakesworth  · 技术社区  · 8 年前

    是否可以在中使用标准数据注释。NET framework(如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()并将值作为字符串返回,但抛出了expetions,说明注释无法将对象(值)强制转换为字符串(即使重写只是这样…?)。

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   andnik    8 年前

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

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

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

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

    将其放在MyProperty类中。

    推荐文章