Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is AttributeUsageAtribute implemented?

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?

like image 998
Rado Avatar asked Oct 26 '25 15:10

Rado


1 Answers

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 { 
}
like image 99
DmitryG Avatar answered Oct 29 '25 03:10

DmitryG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!