2010-05-21 9 views
6

J'ai deux attributs personnalisés définis comme ceci:Est-ce que la restriction d'attributs à la classe ou aux propriétés est réalisable?

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; } 
} 

Je voudrais limiter la SchemaAttribute aux classes, et la AttributeAttribute aux propriétés.

Est-ce faisable?

+0

Si vous trouvez ma question si assez bon pour aider quelqu'un d'autre, s'il vous plaît upvote. Merci! =) –

Répondre

10

Consultez AttributeUsage et AttributeTargets.

Ça va ressembler à quelque chose comme:

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

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

+1 - Beaucoup mieux que le mien. –

4

Regardez AttributeTargetAttribute

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

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

+1 Merci pour votre réponse! =) –