将属性限制为类或属性是否可行?

Wil*_*ler 8 c# vb.net attributes custom-attributes .net-2.0

我有两个自定义属性定义如下:

internal class SchemaAttribute : Attribute {
    internal SchemaAttribute(string schema) {
        Schema = schema;
    }

    internal string Schema { get; private set; }
}

internal class AttributeAttribute : Attribute {
    internal AttributeAttribute(string attribute) {
        Attribute = attribute;
    }

    internal string Attribute { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

我想将SchemaAttribute限制为类,将AttributeAttribute限制为属性.

这可行吗?

Jus*_*ner 14

查看AttributeUsageAttributeTargets.

它看起来像:

[AttributeUsage(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
{
    // Implementation
}

[AttributeUsage(AttributeTargets.Property)]
internal class AttributeAttribute : Attribute
{
    // Implementation
}
Run Code Online (Sandbox Code Playgroud)