开发者

Get derived class properties in base Static method - RIDDLE! :)

开发者 https://www.devze.com 2023-03-06 05:06 出处:网络
I wanted to elaborate on the current project i\'m working on but that would be kind long. Instead I\'ll just post a programming riddle which basically explains what i\'m trying to accomplish. :)

I wanted to elaborate on the current project i'm working on but that would be kind long. Instead I'll just post a programming riddle which basically explains what i'm trying to accomplish. :)

abstract class A
{
    // key = Derived Class name, value = list of properties the derive class exposes.
    private static Dictionary<string, List<string>> _DerivedPropertyNames;

    static A()
    {
        InitializeDerivedPropertyNames();
    }

    private static void InitializeDerivedPropertyNames()
    {
        //...???...
    }
}

The riddle is how can you create an abstract base class which will hold a static cache of all its derived classes开发者_Python百科 properties?

Note that the idea is to avoid loading an assembly by name.


There is no easy (efficient) way to do this in the base class.
Simply implement a static constructor in every derived class and use it to register the properties.

Also take a look at Dependency properties in the WPF Fx, for comparison.


If you can wait for instances of the child types to be instantiated, then you could use A's regular constructor to register the implementing class:

public A()
{
    Type childType = GetType();
    string className = childType.Name;
    if (!_DerivedPropertyNames.ContainsKey(className)) {
         // add properties for this class
    }
}

It will be very difficult for you to get the job done in the static constructor, before any instantiation, without adding logic in the child classes (which I suppose you don't want). The reason is that you won't be able to enforce all assemblies containing types that implement A to be loaded when A's static constructor is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消