MaxLength数据注释可以与List< T>一起使用吗? [英] Does MaxLength data annotation work with List<T>?
问题描述
可以将 [MaxLength()]
属性与字符串和简单数组一起使用:
One can use [MaxLength()]
attribute with strings and simple arrays:
即 :
[MaxLength(500)]
public string ProductName { get; set; }
或
[MaxLength(50)]
public string [] Products { get; set; }
但是它可以与列表一起使用吗?
But can it be used with a List?
即 :
[MaxLength(50)]
public List<string> Types { get; set; }
推荐答案
查看源代码,这取决于所使用的.NET版本.
Looking at the source code, it depends on which .NET version is being used.
-
在.NET框架中,它尝试将对象强制转换为
Array
.因此,如果不是(例如,List
),则会引发 InvalidCastException.(源)
In .NET framework, it attempts to cast the object as
Array
. Therefore, if it isn't (e.g.,List<T>
), an InvalidCastException will be raised. (source)
在.NET Core中,源)>
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. Therefore, it should work on any object that implements ICollection
(which List<T>
does) or any object with an int Count
property. (source)
很明显,在这两种情况下,它都会先检查对象是否为字符串,然后再进行收集.
Obviously, in both cases, it first checks if the object is a string before going after a collection.
注意: MinLength
数据注释.
这篇关于MaxLength数据注释可以与List< T>一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!