I have a 2 part question.
First, as the title says, does anybody know how AttributeUsageAtribute is implemented? It can only be applied to a class that derives from Attribute and if not, it will error out with: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute
Second, can I write a similar Attribute that can be applied to classes that derive from a specific class or implement a specific interface?
1) this is compiler specific
2)you can try the following trick:
var attributes = typeof(A).GetCustomAttributes(A.GetDerivedFromAOnlyAttributeType(), false);
// using an attribute outside the A class
class A {
protected class DerivedFromAOnlyAttribute : Attribute { }
public static Type GetDerivedFromAOnlyAttributeType() {
return typeof(DerivedFromAOnlyAttribute);
}
}
[A.DerivedFromAOnly] //ok
class B : A {
}
[A.DerivedFromAOnly] //error
class C {
}
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