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 string Attribute { get; private set; }
}
I would like to restrict the SchemaAttribute to classes, and the AttributeAttribute to properties.
Is this doable?
Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With