简体   繁体   中英

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.

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.

如果用“force”,你的意思是“编译时执行”:你不能。

As Daniel said, you cannot enforce attributes at compile time.

But if you want to read the data at runtime, why bother with attributes and reflection at all? You can create an abstract method in your abstract class:

abstract class Base
{
    public abstract string Metadata();
}

class Derived1 : Base
{
    public override string Metadata()
    {
        return "Metadata for Derived1";
    }
}

class Derived2 : Base  // won't compile, since Metadata has not been provided
{
}

The behaviour is slightly different, of course. With this option, you need a reference to an instance of the derived class instead of just the type information itself. On the other hand, it avoids reflection.

As Daniel says you can't force at compile time. You could add the attribute(s) to the abstract parent and pick them up.

Another option is to add a method to check for the existence of the attrribute in the parent class and throw an exception if not present. Call that from suitable methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM