GCy*_*ala 6 c# data-annotations
我想弄清楚是否有适当的方法可以使用 DataAnnotations 实现这一点:
有一个数组或字符串列表,其中数组或列表中的最大元素数为 2 个项目,并且每个字符串可能只有 255 个字符长。这是否有效:
[MaxLength(2)]
[StringLength(255)]
public string[] StreetAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)
我宁愿不必创建一个新类来保存一个字符串Value属性来将每个字符串限制为 255 个字符。
这是字符串列表的自定义属性:
public class StringLengthListAttribute : StringLengthAttribute
{
public StringLengthListAttribute(int maximumLength)
: base(maximumLength) { }
public override bool IsValid(object value)
{
if (value is not List<string>)
return false;
foreach (var str in value as List<string>)
{
if (str.Length > MaximumLength || str.Length < MinimumLength)
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)