MaxLength 数据注释是否适用于 List<T>?

Does MaxLength data annotation work with List<T>?

可以对字符串和简单数组使用 [MaxLength()] 属性:

:

[MaxLength(500)]
public string ProductName { get; set; }

[MaxLength(50)]
public string [] Products { get; set; }

但是它可以与列表一起使用吗?

:

[MaxLength(50)]
public List<string> Types { get; set; }

查看源代码,这取决于使用的是哪个.NET版本。

  • 在 .NET Framework 中,它尝试将对象转换为 Array。因此,如果不是(例如 List<T>),将引发 InvalidCastException。 (source)

  • 在 .NET Core 中,it calls a method named TryGetCount() which attempts to cast as ICollection and if that fails, it uses reflection to get the Count property. Therefore, it should work on any object that implements ICollection (which List<T> does) or any object with an int Count property. (source)

显然,在这两种情况下,它都会先检查对象是否为字符串,然后再进行收集。

注:同理MinLength data annotation