一个可以用[MaxLength()]
具有字符串和简单数组的属性:
i.e.:
[MaxLength(500)]
public string ProductName { get; set; }
Or
[MaxLength(50)]
public string [] Products { get; set; }
但它可以与 List 一起使用吗?
i.e.:
[MaxLength(50)]
public List<string> Types { get; set; }
查看源代码,这取决于所使用的.NET版本。
-
在.NET框架中,它尝试将对象转换为Array
。因此,如果不是(例如,List<T>
),将引发 InvalidCastException。 (source https://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/MaxLengthAttribute.cs,69)
-
在 .NET Core 中,它调用一个方法 https://source.dot.net/#System.ComponentModel.Annotations/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs,81 named TryGetCount()
它试图投射为ICollection
如果失败,它会使用反射来获取Count
财产。因此,它应该适用于任何实现ICollection
(which List<T>
)或任何带有int Count
财产。 (source https://source.dot.net/#System.ComponentModel.Annotations/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs,120)
显然,在这两种情况下,它首先检查对象是否是字符串,然后再进行集合。
Note:同样适用于MinLength数据注释 https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.minlengthattribute.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)