开发者

Is restricting attributes to class or properties doable?

开发者 https://www.devze.com 2022-12-31 11:38 出处:网络
I have two custom attributes defined like so: internal class SchemaAttribute : Attribute { internal SchemaAttribute(string schema) {

I have two custom attributes defined like so:

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 s开发者_如何学编程tring Attribute { get; private set; }
}

I would like to restrict the SchemaAttribute to classes, and the AttributeAttribute to properties.

Is this doable?


Check out AttributeUsage and AttributeTargets.

It'll look something like:

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

[AttributeUsage(AttributeTargets.Property)]
internal class AttributeAttribute : Attribute
{
    // Implementation
}


Look at AttributeTargetAttribute

[AttributeTarget(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
...

[AttributeTarget(AttributeTargets.Property)]
internal class AttributeAttribute: Attribute
...
0

精彩评论

暂无评论...
验证码 换一张
取 消