gpt4 book ai didi

c# - MaxLength 数据注释是否适用于 List

转载 作者:行者123 更新时间:2023-12-03 20:00:25 25 4
gpt4 key购买 nike

一个可以用[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 框架中,它尝试将对象强制转换为 Array .因此,如果不是(例如, List<T> ),则会引发 InvalidCastException。 ( source )
  • 在 .NET Core 中,it calls a method命名 TryGetCount()试图转换为 ICollection如果失败,它会使用反射来获取 Count属性(property)。因此,它应该适用于任何实现 ICollection 的对象。 (这是 List<T>)或任何带有 int Count 的对象属性(property)。 ( source )

  • 显然,在这两种情况下,它首先检查对象是否是一个字符串,然后再进行集合。
    注: MinLength data annotation 也是如此.

    关于c# - MaxLength 数据注释是否适用于 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67433642/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com