我们基本上是在调用一个类的构造函数:
StringLengthAttribute 是一个类,它的构造函数有一个名为int 的参数maximumLength
还有一些Properties:
-
ErrorMessage 类型为 string
- 在我们的例子中是字符串:
"The {0} must be at least {2} characters long."
-
ErrorMessageResourceName 类型为 string
-
ErrorMessageResourceType 类型为 System.Type
-
MinimumLength 类型为 int
ErrorMessageResourceName 字符串(还)与其他属性无关,所以它不是这样的:
String.Format("some variable {0} and some other {1}...", 100, 6)
所以数字100 和属性MinimumLength = 6 是根本不是(尚未)发送以使用字符串"The {0} must be at least {2} characters long." 格式化的参数。
StringLengthAttribute 类也有一些方法,其中之一叫做FormatErrorMessage
这个方法在内部调用来格式化消息,它在内部使用String.Format格式化字符串,这里是当参数被传递给字符串被正确格式化的时候。
- {0} 已绑定到 DisplayName
- {1} 绑定到最大长度
- {2} 绑定到 MinimumLength
这是内部调用的方法(如果你想知道它是如何在内部调用的):
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage"/>
/// </summary>
/// <param name="name">The name to include in the formatted string</param>
/// <returns>A localized string to describe the maximum acceptable length</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
public override string FormatErrorMessage(string name) {
this.EnsureLegalLengths();
bool useErrorMessageWithMinimum = this.MinimumLength != 0 && !this.CustomErrorMessageSet;
string errorMessage = useErrorMessageWithMinimum ?
DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : this.ErrorMessageString;
// it's ok to pass in the minLength even for the error message without a {2} param since String.Format will just
// ignore extra arguments
return String.Format(CultureInfo.CurrentCulture, errorMessage, name, this.MaximumLength, this.MinimumLength);
}
参考资料:
- 微软参考源here
- 关于 Stackoverflow 的类似问题:“stringlength 属性 errormessage 采用哪些参数?” here
-
StringLengthAttribute Class here 的几乎没用的 msdn 文档