C#, implement 'static abstract' like methods

后端 未结 7 2037
一生所求
一生所求 2020-12-06 08:48

I recently ran into a problem where it seems I need a \'static abstract\' method. I know why it is impossible, but how can I work around this limitation?

For example

相关标签:
7条回答
  • 2020-12-06 09:46

    If you don't mind deferring to implementations to sensibly implement the Description property, you can simply do

    public abstract string ClassDescription {get; } 
    // ClassDescription is more intention-revealing than Description
    

    And implementing classes would do something like this:

    static string classDescription="My Description for this class";
    override string  ClassDescription { get { return classDescription; } }
    

    Then, your classes are required to follow the contract of having a description, but you leave it to them to do it sensibly. There's no way of specifying an implementation in an object-oriented fashion (except through cruel, fragile hacks).

    However, in my mind this Description is class metadata, so I would prefer to use the attribute mechanism as others have described. If you are particularly worried about multiple uses of reflection, create an object which reflects over the attribute that you're concerned with, and store a dictionary between the Type and the Description. That will minimize the reflection (other than run time type inspection, which isn't all that bad). The dictionary can be stored as a member of whatever class that typically needs this information, or, if clients across the domain require it, via a singleton or context object.

    0 讨论(0)
提交回复
热议问题