Force attribute usage in subclass of abstract superclass

冷暖自知 提交于 2019-11-30 23:04:59

问题


How can I force a subclass to implement certain Attributes of its superclass? The reason is that I want to use Attributes for general information about the class, e.g. "DisplayName", "Description" or "Capabilities".

So I thought I might implement them in a superclass and force the subclasses to implement the attributes.

Is there something like an abstract attribute like for methods?

[abstract DeclareMe]
public abstract class InheritMe {
    public abstract void DeclareMe();
}

回答1:


As your class must be run sooner or later, you can add checking mechanism to your base class to verify the existance of certain attributes in your sub classes.

Here's some sample code for you.

class Program
{
    static void Main(string[] args)
    {
        var a = new SubA();
        var b = new SubB();
    }
}

class BaseClass
{
    public BaseClass()
    {
        Type t = GetType();
        if (t.IsDefined(typeof(SerializableAttribute), false) == false)
        {
            Console.WriteLine("bad implementation");
            throw new InvalidOperationException();
        }
        Console.WriteLine("good implementation");
    }
}

[Serializable]
class SubA : BaseClass
{ }

class SubB : BaseClass
{ }

The last word, don't be too wary of yourself. Once I was doing my design, I always thought I might call two methods in a wrong order or forget to do something, then I turned a simple design into a complicated one to prevent my possible mistakes. Later I threw away the guards, just throwing Exceptions and the code used to detect unexpected situations were surrounded by #if DEBUG.




回答2:


In addition to the answers from that other thread:

You could use FxCop and implement a custom rule that checks if your attributes are present.



来源:https://stackoverflow.com/questions/11409031/force-attribute-usage-in-subclass-of-abstract-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!