C# 如何重用属性

C# 如何重用属性,c#,C#,所以我创建了一个类,比如 public static class SharedDataAnnotations { /// <summary> /// Matches letters, digits, dashes, underscores and spaces. /// </summary> public static RegularExpressionAttribute DisplayNameProperCharacters =

所以我创建了一个类,比如

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." };
}
但是当我试着把它放在一个像

[SharedDataAnnotations.DisplayNameProperCharacters]
我得到了错误

“SharedDataAnnotations”不包含的定义 'DisplayNamePropertCharacters'


属性必须是类型名。根据库正在阅读的内容,可以使用接口或基类进行装饰。您还可以将regex值定义为常量字符串以供重用。

属性必须是typename。根据库正在阅读的内容,可以使用接口或基类进行装饰。您还可以将regex值定义为常量字符串以供重用。

您不能。属性对象本身需要是其应用到的每个代码元素的新实例

在构造自定义属性时,也不能引用非文字值。因此,无法将对
DisplayNamePropertCharacters
对象的引用传递给自定义属性构造函数


您可以做的是让自定义属性将某个标识符(例如字符串、枚举值等)作为其构造函数的参数,该标识符指定您实际需要的行为(例如,在适当的时间查找特定的
RegexExpressionAttribute
对象)。

您不能。属性对象本身需要是其应用到的每个代码元素的新实例

在构造自定义属性时,也不能引用非文字值。因此,无法将对
DisplayNamePropertCharacters
对象的引用传递给自定义属性构造函数

您可以做的是让自定义属性将一些标识符(例如字符串、枚举值等)作为其构造函数的参数,这些标识符指定您实际需要的行为(例如,在适当的时间查找特定的
RegexExpressionAttribute
对象)

[SharedDataAnnotations.DisplayNameProperCharacters]