所以我创建了一个类似
的类public static class SharedDataAnnotations
{
/// <summary>
/// Matches letters, digits, dashes, underscores and spaces.
/// </summary>
public static RegularExpressionAttribute DisplayNameProperCharacters =
new RegularExpressionAttribute(@"^[A-Za-z0-9\-_ ]+$") { ErrorMessage = "Display name can only contain letters, numbers, underscores, dashes and spaces." };
}
因为我希望能够重复使用
[RegularExpression("@"^[A-Za-z0-9\-_ ]+$"", ErrorMessage = "Display name can only contain letters, numbers, underscores, dashes and spaces.")]
然而,当我尝试将它放在像
这样的属性上时[SharedDataAnnotations.DisplayNameProperCharacters]
我收到错误
&#39; SharedDataAnnotations&#39;不包含的定义 &#39; DisplayNameProperCharacters&#39;
答案 0 :(得分:0)
属性必须是typename。根据读取的库,您可以使用接口或基类进行装饰。您还可以将正则表达式值定义为常量字符串以供重用。
答案 1 :(得分:0)
你不能。属性对象本身需要是它应用的每个代码元素的新实例。
构建自定义属性时,您也无法引用非文字值。因此,您无法将对DisplayNameProperCharacters
对象的引用传递给自定义属性构造函数。
你可以做的是将自定义属性作为其构造函数的一个参数,将一些标识符(例如字符串,枚举值等)指定为您实际需要的行为(例如,在适当的时间提出特定的RegexExpressionAttribute
对象。