2010-05-21 16 views
6

que tienen dos atributos personalizados definidos así:¿Es posible restringir los atributos a clase o propiedades?

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

quisiera restringir el SchemaAttribute a las clases, y el AttributeAttribute a las propiedades.

¿Es esto factible?

+0

Si encuentra mi pregunta si es lo suficientemente bueno para ayudar a otra persona, por favor upvote. ¡Gracias! =) –

Respuesta

10

Consulte AttributeUsage y AttributeTargets.

Se verá algo como:

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

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

+1 - Mucho mejor que el mío. –

4

Mira AttributeTargetAttribute

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

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

+1 ¡Gracias por tu respuesta! =) –

Cuestiones relacionadas