简体   繁体   English

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

[英]Does MaxLength data annotation work with List<T>?

One can use [MaxLength()] attribute with strings and simple arrays:可以将[MaxLength()]属性与字符串和简单的 arrays 一起使用:

ie :

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

Or或者

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

But can it be used with a List?但它可以与列表一起使用吗?

ie :

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

Looking at the source code, it depends on which .NET version is being used.查看源代码,这取决于使用的是哪个 .NET 版本。

  • In .NET framework, it attempts to cast the object as Array .在 .NET 框架中,它尝试将 object 转换为Array Therefore, if it isn't (eg, List<T> ), an InvalidCastException will be raised.因此,如果不是(例如List<T> ),则会引发 InvalidCastException。 ( source ) 来源

  • In .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.在 .NET Core 中, 它调用一个名为TryGetCount()的方法,该方法尝试转换为ICollection ,如果失败,它使用反射来获取Count属性。 Therefore, it should work on any object that implements ICollection (which List<T> does) or any object with an int Count property.因此,它应该适用于任何实现ICollectionList<T>执行)的 object 或任何具有int Count属性的 object。 ( source ) 来源

Obviously, in both cases, it first checks if the object is a string before going after a collection.显然,在这两种情况下,它首先检查 object 是否是一个字符串,然后再进行收集。

Note: The same goes for MinLength data annotation .注意: MinLength数据注释也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM