MaxLength数据注释可以与List< T>一起使用吗? [英] Does MaxLength data annotation work with List<T>?

查看:61
本文介绍了MaxLength数据注释可以与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&lt; T&gt;一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆