Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Attribute Declaration in Derived Classes

I recently read about attributes and reflection and I thought it would be a good method to include metadata in my program. I have this abstract class and I wanted all classes inheriting from it to declare with the class some attribute, since I wanted custom components(those derived classes) to be created for my program and wanted to read the metadata of these classes on runtime. However, the derived classes all have to explicitly declare the attribute in which I store metadata. So how to I force an attribute declaration in the derived classes? Thanks.

like image 510
resgh Avatar asked Jan 19 '12 13:01

resgh


People also ask

Does a derived class object has all the attributes of its base class?

The derived class contains all the attributes and methods of the base class plus any additional specifications of the derived class. Any changes made to base classes are propagated to all derived classes unless explicitly overridden.

How to inherit a base class in C#?

Inheritance (Derived and Base Class) In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class. Base Class (parent) - the class being inherited from.

What is derived class in C#?

The class that inherits the members of the base class is called the derived class. C# and . NET support single inheritance only. That is, a class can only inherit from a single class.

What is the connection between the base class and the derived class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.


1 Answers

Define your attribute class to itself have an AttributeUsageAttribute attribute where the Inherited property is true.

Or don't, since that's the default...

Derived targets (that is, classes if the attribute is on a class, methods if it is on a method, etc.) will then inherit the attribute without explicit declaration.

like image 99
Jon Hanna Avatar answered Oct 04 '22 00:10

Jon Hanna