C# 字符串长度验证特性 StringLength 实现
以下是特性 StringLength 的代码:
[AttributeUsage(AttributeTargets.Property)]
public class StringLength : AbstractValidateAttribute
{
private int _maxLength;
public StringLength(int maxLength)
{
_maxLength = maxLength;
}
public override bool Validate(object value)
{
if (value is string)
{
string strValue = (string)value;
return strValue.Length <= _maxLength;
}
return true;
}
}
这个特性继承了 AbstractValidateAttribute,重写了 validate 方法,用于判断字符串属性的长度是否超过了 maxLength。它只能作用于属性上,构造时需要传入一个整数表示最大长度。在 validate 方法中,首先判断传入的值是否是字符串类型,如果是,则判断字符串长度是否超过了最大长度,否则直接返回 true。
原文地址: https://www.cveoy.top/t/topic/nIP2 著作权归作者所有。请勿转载和采集!